2021年1月19日星期二

memory for array initialization with string literal

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 memory allocations because a and &a both gives the same address.

How will we prove we have 2 different memories one for array a and other for string literal separately in this scenario?

link to clone: https://onlinegdb.com/HkJhdSHyd

https://stackoverflow.com/questions/65803926/memory-for-array-initialization-with-string-literal January 20, 2021 at 02:06PM

没有评论:

发表评论