What is the difference between these two in terms of memory allocation.
char *p1 = "hello";
char p2[] = "hello";
What is the difference between these two in terms of memory allocation.
char *p1 = "hello";
char p2[] = "hello";
The first one creates a pointer variable (four or eight bytes of storage depending on the platform) and stores a location of a string literal there, The second one creates an array of six characters (including zero string terminator byte) and copies the literal there.
You should get a compiler warning on the first line since the literal is const
.
The first one is a non-const pointer to const (read-only) data, the second is a non-const array.
Since the first one is a non-const pointer to const (read-only) data, the second is a non-const array, as Paul said, you can write:
p2[2]='A'; //changing third character - okay
But you cannot write:
p1[2]='A';//changing third character - runtime error!
The first line is assigning a string(an array of characters) to a constant (meaning you cant change the value without getting a segmentation fault) array of characters , char* essentially points to a character ( or array of bytes if its was allocated multiple character ) in memory. In the second line you are creating an array of characters ( think the same thing as the first as ,they both point to a place in memory where everything is located) , but this time , you can change the values being held within without getting a segmentation fault , as it is non-constant .