开发者

Are inline string arrays in C allocated on the stack?

开发者 https://www.devze.com 2023-01-25 19:43 出处:网络
In C, consider the following \"inline\" string arrays: char *string1 = \"I\'m a literal!\"; char *string2 = malloc((strlen(string1) + 1) * sizeof(char));

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 segment
  • string2 pointer is on the stack, its value is the address of a memory block allocated on the heap
  • string3 is an array which occupies 4 * sizeof(char) bytes on the stack
  • stringArray is an array which occupies 3 * 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消