I was going through this QA where it is said that char
array when initialized with string literal will cause two memory allocations one for variable and other for string literal.
I have written below program to see how is the memory allocated.
#include <stdio.h>
#include <string.h>
int main()
{
char a[] = "123454321";
printf("a =%p and &a = %p\n", a, &a);
for(int i = 0; i< strlen(a); i++)
printf("&a[%d] =%p and a[%d] = %c\n",i,&a[i],i,a[i]);
return 0;
}
and the output is:
a =0x7ffdae87858e and &a = 0x7ffdae87858e
&a[0] =0x7ffdae87858e and a[0] = 1
&a[1] =0x7ffdae87858f and a[1] = 2
&a[2] =0x7ffdae878590 and a[2] = 3
&a[3] =0x7ffdae878591 and a[3] = 4
&a[4] =0x7ffdae878592 and a[4] = 5
&a[5] =0x7ffdae878593 and a[5] = 4
&a[6] =0x7ffdae878594 and a[6] = 3
&a[7] =0x7ffdae878595 and a[7] = 2
&a[8] =0x7ffdae878596 and a[8] = 1
From the output it does not look like we have two separate memory locations for array and string literal.
If we have separate memory for array and string literal, is there any way we can prove array a
and string literal stores separately in this scenario?
link to clone: https://onlinegdb.com/HkJhdSHyd