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?

2
  • When you use %p specification then do not forget to cast the argument to void *: printf("a = %p, &a = %p\n", (void *)a, (void *)&a). Commented May 7, 2019 at 10:20
  • 1
    a is not a const pointer; it is an array. Have a look at the duplicates. Commented May 7, 2019 at 10:48

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@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...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.