1

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

Could someone maybe help me explain array decaying? In specific, I was confused about 1) how does an array refer to itself, and 2) is it true that, when I define

int array[] = { 45, 67, 89 };

then array, &array,and &array[0] all refer to this array? I found out they appear as the same outputs when printed, but are they also referring to exactly the same thing in memory?

Community
  • 1
  • 1
nemesis
  • 253
  • 1
  • 4
  • 11

3 Answers3

8

then array, &array,and &array[0] all refer to this array?

The memory location will be the same, but the types will be different.

  • array is just that: an array of 3 integers
  • &array has type int (*)[3], a pointer to an array
  • &array[0] has type int *, a pointer to a single integer
cnicutar
  • 178,505
  • 25
  • 365
  • 392
2

array, in value contexts is a of type int *, and the pointer points to the first element of the array. &array, is of type "pointer to an array [3] of int" and points to the whole array. &array[0] is of type int *, and points to the first element of the array.

So, &array[0] is the same as array, if array is used in value context. One situation where array is not used in value context is in sizeof operator. So: sizeof array will be different from sizeof &array[0].

Let's take an example:

int array[] = { 45, 67, 89 };
int *pa = array; /* pa is now pointing to the first element of "array" */
int *pb = &array[0]; /* pb is also pointing to the same */
int (*pc)[3] = &array; /* pc points to the whole array.
                          Note the type is not "int *" */

printf("%zu\n", sizeof &array[0]); /* prints size of an "int *" */
printf("%zu\n", sizeof array); /* prints 3 times the size of an int */
printf("%zu\n", sizeof &array); /* prints size of pointer to an array[3] of int */

See also: http://web.torek.net/torek/c/pa.html

Alok Singhal
  • 93,253
  • 21
  • 125
  • 158
0

They all refer to same memory location but little differently. array and &array refer the entire array starting with the address of first element, while &array[0] refers the first element only in the array.

Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73