0

The name of a string in C is a constant value that contains the address to the first element of the string. Now my question is: why this constant variable and his pointer contains the same address?

char str[] = "hola";
printf("%p %p", &str, str);

The output of this code is :

0x7ffc9ab53f43 0x7ffc9ab53f43

but i was expecting to read two different addresses.

Some programmer dude
  • 380,411
  • 33
  • 383
  • 585

2 Answers2

1

Lets take a look at how your array is stored in memory (with pointers to elements inserted):

+--------+--------+--------+--------+--------+
| str[0] | str[1] | str[2] | str[3] | str[4] |
+--------+--------+--------+--------+--------+
^
|
&str[0]
|
&str

The pointer &str[0] (which is what str decays to) points to the first element of the array. The first element of the array is also the address of the array itself. Therefore (void *) &str[0] == (void *) &str is true.

Some programmer dude
  • 380,411
  • 33
  • 383
  • 585
0

See this link Pointer address in a C array

and try this code (it helps me to understand deeply the problem)

#include<stdio.h>

int main()
{
int arr[] = {1,2,3,4,5};
int (*ptr2)[sizeof(arr)/sizeof(*arr)] = &arr;

printf("%d\n",sizeof(arr));
printf("%d\n",sizeof(*arr));
printf("%d\n",sizeof(ptr2));
printf("%d\n",sizeof(*ptr2));
}
Sourav Ghosh
  • 130,437
  • 16
  • 177
  • 247
Stef1611
  • 1,482
  • 10
  • 22