Reputation: 93
When we do
char *p ="house";
p = 'm';
Its not allowed.
But when we do
char p[] = "house";
p[0] = 'm';
printf(p);
It gives O/P as : mouse
I am not able to understand how and where C does memory allocation for string literals?
Upvotes: 2
Views: 3322
Reputation: 22823
char p[] = "house";
"house"
is a string literal stored in a read only location, but, p is an array of chars placed on stack in which "house"
is copied.
However, in char *p = "house";
, p
actually points to the read-only location which contains the string literal "house", thus modifying it is UB.
A note from the standard 6.7.8 Initialization
14 An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
So you basically have an array of characters. It should not be so difficult or puzzle you in understanding how this array gets modified if you have used arrays of ints
, floats
etc.
Upvotes: 6
Reputation: 34625
char *p = "house"; // const char* p = "house";
String literal "house"
resides in read only location and cannot be modified. Now what you are doing is -
*p = 'm' ; // trying to modify read-only location; Missed the dereferencing part
Now,
char p[] = "house";
"house"
is copied to the array p. So, it's contents are modifiable. So, this actually works.
p[0] = 'm'; // assigning `m` at 0th index.
Upvotes: 0
Reputation: 23858
When you use char *p="house" - the compiler collects all the "house" strings and puts them in one read only space.
When you use char p[]="house" the compiler creates space for the string as an array in the local scope.
Basic difference is that 1000's of pointer could share the first one (which is why you cannot modify) and the second is local to the scope - so as long as it stays the same size it is modifiable.
Upvotes: 0