Explanation of Array Pointers in c?

1

Possible Duplicate:
C: How come an array’s address is equal to its value?
C pointer : array variable

Considering a multidimensional Array:

int c[1][1];

Why all of the following expression points to the same address??

printf("%x", (int *) c);      // 0x00000500
printf("%x", *c);             // 0x00000500
printf("%x", c);              // 0x00000500

How would a pointer's actual value and it's derefernced value can be the same?

c
pointers
multidimensional-array
asked on Stack Overflow Oct 10, 2012 by zeronone • edited May 23, 2017 by Community

3 Answers

1

You just have to think: where is the first position on this array?

Suppose it's on 0x00000050 in your memory space. What is the first item in your array? It's c[0][0], and its address is 0x00000050. Sure enough, the address of the first position is the same of the array. Even if you do c[0] only, it still points to the same address, as long as you cast it to the right type.

But you should not confuse pointers to arrays.

answered on Stack Overflow Oct 10, 2012 by Toribio
1

Under most circumstances1, an expression of type "N-element array of T" will be converted ("decay") to expression of type "pointer to T", and the value of the expression will be the address of the first element in the array.

The expression c has type int [1][1]; by the rule above, the expression will decay to type int (*)[1], or "pointer to 1-element array of int", and its value will be the same as &c[0]. If we dereference this pointer (as in the expression *c), we get an expression of type "1-element array of int", which, by the rule above again, decays to an expression of type int *, and its value will be the same as &c[0][0].

The address of the first element of the array is the same as the address of the array itself, so &c == &c[0] == &c[0][0] == c == *c == c[0]. All of those expressions will resolve to the same address, even though they don't have the same types (int (*)[1][1], int (*)[1], int *, int (*)[1], int *, and int *, respectively).


1 - the exceptions to this rule are when the array expression is an operand of the sizeof, _Alignof, or unary & operators, or is a string literal being used to initialize another array in a declaration

answered on Stack Overflow Oct 10, 2012 by John Bode
0

How would a pointer's actual value and it's derefernced value can be the same
It's not a pointer, it's an array.

See Q&A #3 & #4

c is the address of the array. c is also the address of the first element.

answered on Stack Overflow Oct 10, 2012 by Mike • edited May 23, 2017 by Community

User contributions licensed under CC BY-SA 3.0