Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char * sharing same memory

Tags:

c

gcc

Here is my code and I need a clarification in the output of this code:

#include <stdio.h>
int main(void )
{
char name1[10] = "Rajan" , name2[10] = "Rajan" ;
char *name3 = "Chennai" , *name4 = "Chennai" ;
printf("\nAddress for name1 and name2 : %p and %p",name1,name2) ;
printf("\nAddress for name3 and name4 : %p and %p",name3,name4) ;
return 0 ;
}

The ouput of this code is

Address for name1 and name2 : 0x7fff9e6cbe10 and 0x7fff9e6cbe20
Address for name3 and name4 : 0x400760 and 0x400760

Here the address of the values name1 and name2 are different since i allocated two different arrays. But in the case of name3 and name4, the address is same, why is it not different? It won't create a different memory and allocate name for the value Chennai? Why is it pointing to the same memory?

like image 300
Rajan Chennai Avatar asked Jul 08 '26 06:07

Rajan Chennai


1 Answers

The standard allows it:

6.4.5 - 7

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

I mean, it shouldn't matter as long as you don't modify them, right ?

like image 124
cnicutar Avatar answered Jul 10 '26 05:07

cnicutar