考虑函数:
char *func()
{
return "Some thing";
}
常量 string
(char
array) "Some thing"
是存储在堆栈中作为函数调用的局部变量还是全局变量堆?
我猜测它在堆中。
如果多次调用该函数,内存中有多少份"Some thing"
? (它是堆还是堆栈?)
最佳答案
字符串文字“Some thing”的类型为const char*
。因此,它们既不在堆上也不在堆栈上,而是在一个只读位置,这是一个实现细节。
来自 Wikipedia
Data
The data area contains global and static variables used by the program that are initialized. This segment can be further classified into initialized read-only area and initialized read-write area. For instance the string defined by char s[] = "hello world" in C and a C statement like int debug=1 outside the "main" would be stored in initialized read-write area. And a C statement like const char* string = "hello world" makes the string literal "hello world" to be stored in initialized read-only area and the character pointer variable string in initialized read-write area. Ex: static int i = 10 will be stored in data segment and global int i = 10 will be stored in data segment
关于c++ - 堆还是栈?当在 C++ 中的函数调用中引用常量字符串时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7440185/