2

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

int a[2];
printf("%u %u", (int)(&a), (int)(a));

I am thinking that &a is a pointer that points to the address of a. And the second a means the beginning address of the array.

Why are they the same?

Community
  • 1
  • 1
Fionser
  • 161
  • 2
  • 8
  • Why cast the addresses to **signed integers** then print them using an **unsigned int format specifier?** You had one job! –  Oct 13 '12 at 06:30
  • After reading the link, should I regards &a[0] as &a ? – Fionser Oct 13 '12 at 06:35
  • @Fionser: No, `&a[0]` is equivalent to `a` (except as the operand to `&` or `sizeof`). – caf Oct 13 '12 at 07:49

3 Answers3

7

In any context except where it is the operand of either the unary & or sizeof operators, the array name a evaluates to a pointer to the first member of the array. This has type int *.

In &a, a still designates the array itself, so &a is the address of the array. This has type int (*)[2].

Since the first element of the array is located at the beginning of the array, the address of the array and the address of the first element are necessarily coincident, so that's why you see the same value.

(Really you should be using the %p format specifier to print pointers).

caf
  • 233,326
  • 40
  • 323
  • 462
2

That's because they all point to the same address.

  • &a is the address of a
  • a is the array itself (the beginning of it)
  • &a[0] is also the same address, because it's the first element

So if you always cast these examples to int, it'll be a's address. By the fact that the first element of the array is always at the beginning address of it, as a alone points to its first element, if type-casted correctly.

Toribio
  • 3,963
  • 3
  • 34
  • 48
0

&a is the base address of array that is constant. and also that a holds the first element.

rbhawsar
  • 805
  • 7
  • 25