473,765 Members | 2,121 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pointer Declaration/Array definition


Why does this declaration give undefined result:

file1: extern char * p;
file2: char p[10];

Let's assume p has been initialized, now accessing p[i]...
Nov 14 '05
12 2398
In article <news:cg******* ***@news-int.gatech.edu> <ur**@ur8x.co m> wrote:
Ok, here is what I want to know: What exactly happens when
p[i] is called, as far accessing and dereferncing that makes
the code wrong (yes, I know it should not work, I just want
to know why).


In some cases, a picture is worth a thousand words. (Be sure to
view this in a fixed-width font.)

void f(void) {
char a[6] = { '1', '2', '3' };
char *p;
...
}

+-----------------------------------+
| '1' | '2' | '3' | 0 | 0 | 0 |
+-----------------------------------+
+-------------------+ /------------->
| <garbage address> |---------/
+-------------------+

The larger box represents "a", which is made up of six bytes (each
char in C is a "C byte", always). The six bytes have known values
because we initialized "a".

The smaller box represents p, the pointer. We did not initialize
it, so (assuming these are inside a function, as in the example
code) it is full of trash. If viewed as a pointer, the result is
unpredictable -- in this case I have drawn it as a "wild pointer"
pointing off into the weeds somewhere.

Now, if we set p to point to the first element of "a":

p = &a[0];

we get a new picture:

+-----------------------------------+
| '1' | '2' | '3' | 0 | 0 | 0 |
+-----------------------------------+
^
|
+--------------------+
|
+-------------------+ |
| <valid address> -|---+
+-------------------+

Now p contains an arrow pointing to &a[0].

When you write a[i], the compiler says to itself: "aha, `a', that
is declared as an array, and you want to do something with the
`value' of `a' -- index it like an array, in this case -- so I will
construct a pointer pointing to &a[0] and use that."

This special rule about arrays is a quirk of C. Many other languages
are very different in their treatment of arrays. There is no
fundamental reason the C language *has* to work this way; it just
does. That means that you simply have to memorize this rule. It
is a thing you have to know about C that has no reason other than
"the guy who wrote the language decided to do it that way" -- rather
like the syntax for declarations.

On the other hand, when you write p[i], the compiler takes the
pointer value p already has -- here, pointing to &a[0] -- and
follows the arrow and then "moves right" according to the number
in "i". Moreover, if you have the variable "p", you can set it
to point to some place other than &a[0]:

p = &a[2];

makes p point to the '3', and p[1] is the first 0 (or '\0' -- same
thing) byte, while p[-2] and p[-1] now exist, naming the '1' and
'2' in a[0] and a[1] respectively. This is because the compiler
generates code that follows the arrow and then "moves right" as
requested, and you have already moved right -- which lets you move
left again, if you want to.

The difference between using a pointer ("p") and using the array
name ("a"), then, is that when you use the array name, the compiler
has to take an extra step to *construct* the pointer it needs, just
so that it can then follow the pointer. Curiously, this extra work
*can* (not necessarily "does", just "can") result in faster machine
code. The reason is that the compiler is allowed to know a lot
more about the pointer it constructed here, *because it constructed
it*. It is not some unknown pointer taken in off the street, with
a mysterious and shady background. The constructed pointer has a
solid pedigree. Of course, given a local variable like "p", a
smart compiler can probably look around and figure out whether "p"
has a similar pedigree -- so on *good* compilers, there tends to
be little if any performance difference. On not-so-good compilers,
it is hard to tell which will be faster -- the array, because the
compiler knows about the pointer it makes, or the pointer, because
the compiler does not have to do the extra "make a pointer" step.
Or perhaps neither will be faster there, either.

The moral of the "performanc e story" above, as it were, is: use
whichever one is clearer to the human programmer. On a good compiler
it will make no real difference, and on a bad one, you cannot predict
what kind of difference it will make.

For more on The Rule about arrays and pointers in C, see also
<http://web.torek.net/torek/c/pa.html>.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #11
<ur**@ur8x.co m> wrote in message
news:cg******** **@news-int.gatech.edu. ..
| Ivan Vecerina <to************ ***********@vec erina.com> wrote:
| > This "implicit conversion" is performed by the compiler, when
| > it knows that an array is being used as if it were a pointer.
| > But the generated code and memory layout is very different.
....
| Thanks. Referring to some other posts, does this "implicit
| conversion" also known as "decaying convention?"

Some like to say that arrays "decay" into pointers,
which illustrates the fact that the conversion is
not (easily) reversed. But I've also seen it use
to designate the fact that function parameters declared
as having an array type are actually treated as pointers.
E.g.:
int f( char param[16] );
is interpreted by the compiler as:
int f( char *param );
hth
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Nov 14 '05 #12
In <cg**********@n ews-int2.gatech.edu > ur**@ur8x.com writes:

Why does this declaration give undefined result:

file1: extern char * p;
file2: char p[10];


Why did you expect anything else? It's the same as:

file1: extern double c;
file2: char c;

All declarations of the same object must match its definition.

If you think that there is anything special about pointers and arrays
in this context, read the FAQ.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
5644
by: pandapower | last post by:
Hi, I know about the equivalence of pointer and arrays.But my doubt comes when its for multidimentional arrays.I have read the C faq but still have some doubts. Suppose I have a declaration as 1. char array or char array and it will get decayed to 2. char *array
7
8735
by: Michael Birkmose | last post by:
Hi everyone!, Are pointers to incomplete types allowed in ANSI C? I can see that pointer arithmic on pointers to incomple types is impossible, however there are situations where it can be useful: consider this:
5
41035
by: Cancerbero | last post by:
Hi (first, excuse me for my bad english) As I know, the semantics for typedef is: typedef A B; I think this makes B a synonym of A, where A is an existing data type. Is that right? Based on the previous definition of typedef, I can't understand the next:
42
5625
by: baumann | last post by:
hi all, typedef int (*pfunc)(int , int); pfunc a_func; i know it's ok, but how can define a_func without typedef statement? thanks .
7
2806
by: Kathy Tran | last post by:
Hi, Could you please help me how to declare an araay of pointer in C#. In my program I declared an structure public struct SEventQ { public uint uiUserData; public uint uiEvent; public uint uiParam0; public uint uiParam1;
73
3846
by: Markus | last post by:
Hi, I can't understand why this code causes a "memory read exception" at int x=**a; void pass(int** a) { int x=**a; } void main()
17
3260
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ================================================================================ /* A function that returns a pointer-of-arrays to the calling function. */ #include <stdio.h> int *pfunc(void);
17
2721
by: Christian Wittrock | last post by:
Hi, What does ANSI C say about casting an 8 bit pointer to a 16 bit one, when the byte pointer is pointing to an odd address? I have detected a problem in the Samsung CalmShine 16 compiler. This compiler I use for the Samsung 16 bit Smartcard chips and I want to know if it is compliant with the ANSI standard or if it violates it. Have a look at this super simple example, where the value of b is incorrect:
42
5344
by: xdevel | last post by:
Hi, if I have: int a=100, b = 200, c = 300; int *a = {&a, &b, &c}; than say that: int **b is equal to int *a is correct????
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9398
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10156
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9951
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8831
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5275
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.