1

If I have an int array intArr[4] and get the address it’s pointing to like so printf("%p\n", intArr,);

Then get the address of the array printf(“%p\n”, &intArr);

Both statements return the same address

0xffffcc14

0xffffcc14

Then when it is de-referenced either through intArr[0] or *intArr it gives an integer value.

So I was wondering what is happening to make it seem as though an array is holding two things at the same time in the same memory location: a pointer value to itself and an element value?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    It doesn't. Array is decaying to a pointer when passed to `printf`, so the value of the address of the *first element* is printed. When `&intArr` is printed - it is the address of the array itself, which is the same as the one of the first element for obvious reasons. – Eugene Sh. Jan 12 '22 at 19:22

1 Answers1

1

The array you declared

intArr[4];

in fact is a named extent of memory. So the address of the array and the address of its first element is the address of the extent of memory occupied by the array.

The only difference between the expressions &intArr and intArr used in the calls of printf is their types. The first expression has the pointer type int ( * )[4] and the second expression has the pointer type int * but the values produced by the expressions are equal each other.

In this call

printf("%p\n", intArr,);

the array designator is implicitly converted to a pointer to its first element.

Arrays used in expressions with rare exceptions as for example using them in the sizeof operator are implicitly converted to pointers to their first elements.

For example if you will write

printf( "%zu\n", sizeof( intArr ) );

you will get the size of the array.

On the other hand, if you will write

printf( "%zu\n", sizeof( intArr + 0 ) );

you will get the size of a pointer because in this expression intArr + 0 the array designator is implicitly converted to a pointer to its first element.

As for these expressions intArr[0] and *intArr then the first expression is evaluated like *( intArr + 0 ) that is the same as *intArr.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thanks I guess what I'm trying to ask then is where is the pointer address stored that the array uses when it decays to a pointer? since **intArr[0]** holds an int value, not the pointer value. I hope that seems different than what I just asked. – user17917376 Jan 13 '22 at 10:10
  • @user17917376 The array address is stored nowhere. The compiler tracks addresses of all variables and the linker resolves them. – Vlad from Moscow Jan 13 '22 at 10:15