Pointer to const string in C
char *p = "string"; //creates pointer to constant string
char p[] = "string"; //just an array with "string"
I'm just a bit confused about why does it in the first example create a pointer to a constant string? Shouldn't it be just a poi开发者_开发问答nter refering to a place in memory with "string"?
In the first case, "string"
may be stored in a read-only area of the process, so attempting to modify the memory pointed to by p
would cause undefined behaviour.
In the second case, actual memory is allocated and initialised on the stack at runtime (or in an appropriate section of the process at program startup if it's not a local variable), so modifying the memory is OK.
The first case can be illustrated like this:
+---+ +---+---+---+---+---+---+---+
| | ----> | s | t | r | i | n | g | \0|
+---+ +---+---+---+---+---+---+---+
p
Whereas the second case is:
+---+---+---+---+---+---+---+
| s | t | r | i | n | g | \0|
+---+---+---+---+---+---+---+
p
The two declarations have a significant difference, although you may have heard that they are the same from low-quality C programming books.
The first is a pointer of type char *
, whereas the second is an array of type char []
. Array identifiers decay to a pointer in some contexts, but that doesn't make them pointers.
A pointer is merely an address and an array is "the whole thing" - in the first case sizeof(p)
yields the size of a pointer (usually 4
or 8
depending on the target machine), and in the second case it yields 7 * sizeof(char)
, the length of the actual string.
It is unfortunately legal in C (and in C++03, for compatibility). But any attempt to modify the string literal via the pointer will result in Undefined behavior. So, better always assign the string literal to a const char*
const char * cp = "Hello"; //OK
char* p = "Hello"; //OK in C and C++03 (unfortunately), Illegal in C++11
cp[0] = 'Y'; //Compile-time error, good
p[0] = 'Y'; //no compiler error, undefined behavior
The first one creates a pointer and sets it to the address of a constant string (presumably in a region that does not have write protection on pages). Writing to this pointer is illegal (and will probably crash).
The second one creates an array and copies characters into it. Writing to this array will write to some location on your stack and is perfectly legal.
In the first case, "string" may be stored in a read-only area of the process, so attempting to modify the memory pointed to by p would cause undefined behaviour.
It can be proved by running the above line of codes repeatedly.
char *p="string";
you will notice that the content of p (i.e. the address of "string") remains constant.
char p[] = "string";
for these memory is allocated hence each time you run content of p changes.
精彩评论