Are inline string arrays in C allocated on the stack?
In C, consider the following "inline" string arrays:
char *string1 = "I'm a literal!";
char *string2 = malloc((strlen(string1) + 1) * sizeof(char));
//Do some string copying
...
char string3[] = {'a','b','c','\0'};
char *stri开发者_如何学编程ngArray[] = {string1, string2, string3};
Would stringArray
simply contain a copy of each of three pointers?
Would the array be allocated on the stack?
The stringArray
is allocated on the stack, each of its element is a pointer to a char
. To be more specific :
string1
pointer is on the stack, its value is the address of the first character of a read-only string in the data segmentstring2
pointer is on the stack, its value is the address of a memory block allocated on the heapstring3
is an array which occupies4 * sizeof(char)
bytes on the stackstringArray
is an array which occupies3 * sizeof(char *)
bytes on the stack.
Yes (it does contain copies of pointers (see later)), and yes (the array is on stack).
(string3
is not a pointer, but rather an array).
Assuming your code fragment is part of a function (and it looks like it is, since you "do some string copying"), then yes, all but the storage for string2 (since it is malloc()ed) would be on the stack.
精彩评论