可能的重复:
C 字符串文字:它们去了哪里? https://stackoverflow.com/questions/2589949/c-string-literals-where-do-they-go
据我所知,
一般来说,指针必须是
由malloc()分配,并且将被分配
到堆,然后通过 free() 取消分配;
and
非指针(int、char、float 等)将是
自动分配到堆栈,并且
只要函数转到就未分配
返回
但是,从以下代码:
#include <stdio.h>
int main()
{
char *a;
a = "tesaja";
return 0;
}
哪里会a
分配给 ?栈还是堆?
字符串literal http://en.wikipedia.org/wiki/Literal_(computer_science)将被分配在数据段 http://en.wikipedia.org/wiki/Data_segment。指向它的指针,a
,将在堆栈上分配。
您的代码最终将被编译器转换为如下所示:
#include <stdio.h>
const static char literal_constant_34562[7] = {'t', 'e', 's', 'a', 'j', 'a', '\0'};
int main()
{
char *a;
a = &literal_constant_34562[0];
return 0;
}
因此,你的问题的确切答案是:neither. Stack, data, bss and heap都是不同的内存区域。 const static 初始化变量将位于data.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)