gpt4 book ai didi

c - C语言中变量存储在堆还是栈上?

转载 作者:行者123 更新时间:2023-11-30 21:48:03 25 4
gpt4 key购买 nike

假设您有代码:

int main(void)
{
int a=10;
char b[10]="HELLO";
const int x=10;
return 0;
}

如有错误,请指正:

“a”将仅存储在堆栈中(根本不在数据段中)及其值(10)

“b”将作为指针存储在堆栈中(因为我认为数组是指向第一个元素的指针),“HELLO”将存储在堆中(就像我们使用 malloc 一样)。

“x”可以存储在数据、堆栈或文本中,具体取决于编译器。

最佳答案

"a" will be stored in the stack only (data segment not possible) with its value(10)

正确。

"b" will be stored as a pointer (because the array is a pointer to the first element) in the stack and "HELLO" will be stored in heap ( like if we are using malloc).

不正确。

将该行视为:

char b[10];
strcpy(b, "HELLO");

b 是一个数组,而不是指针。堆栈内存用于数组。

"x" can be stored in data, stack, or text depending on compiler.

正确。

关于c - C语言中变量存储在堆还是栈上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43856132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com