0

In this code,

int a[] = {1, 2, 3, 4, 5};
printf("a = %p, &a = %p\n", a, &a);

same address for a and &a is printed. As I know, a is a const pointer to 0th element of array. Why address of a and contents of it are equal?

1 Answers1

2

Why address of a and contents of it are equal?

They are not.

In most of the cases, a variable of type array decays to a pointer to the first element. Thus

printf("1. %p, 2. %p", (void*)a, (void *)&a[0]);

will print same values.

That said, the address of an array, is the same as the address of the first element of the array, thus

 printf("1. %p, 2. %p", (void*)a, (void*)&a);

also prints the same value. However, remember, they are not of the same type.

  • a, which is same as &a[0] in this case, is of type int *
  • &a, is of type int *[5], i.e, a pointer to an array of 5 ints.
klutt
  • 30,332
  • 17
  • 55
  • 95
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • How a is stored in memory? Any pointer variable, is 4 (or 8) byte in memory, with value = address of variable that pointer points to. Is it incorrect about array name? – Yousef Rashidi May 07 '19 at 10:26
  • @yousefrashidi it is not stored in memory at all. C.f. *"How is the address of `int a` stored in memory?! Doesn't every `int a` actually need 12 bytes of memory, 4 for the `a` and 8 for its address?!" And where is this address stored?" Pointers all way down...* – Antti Haapala -- Слава Україні May 07 '19 at 10:33