Tuesday 8 November 2011

What is the difference between array_name and &array_name? in C programming

What is the difference between array_name and &array_name?

One is a pointer to the first element in the array; the other is a pointer to the array as a whole.

NOTE

It’s strongly suggested that you put this book down for a minute and write the declaration of a variable that points to an array of MAX characters. Hint: Use parentheses. If you botch this assignment, what do you get instead? Playing around like this is the only way to learn the arcane syntax C uses for pointers to complicated things. The solution is at the end of this answer.

An array is a type. It has a base type (what it’s an array of ), a size (unless it’s an “incomplete” array), and a
value (the value of the whole array). You can get a pointer to this value:

char a[ MAX ]; /* array of MAX characters */
char *p; /* pointer to one character */
/* pa is declared below */
pa = & a;
p = a; /* = & a[ 0 ] */

After running that code fragment, you might find that p and pa would be printed as the same value; they both
point to the same address. They point to different types of MAX characters.

The wrong answer is
char *( ap[ MAX ] );
which is the same as this:
char *ap[ MAX ];
This code reads, “ap is an array of MAX pointers to characters.”

Cross Reference:

None.

No comments:

Post a Comment