gpt4 book ai didi

c - 如何防止编译器在循环中对变量使用相同的地址

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:27 25 4
gpt4 key购买 nike

在这段代码中

#include <stdio.h>

int main ()
{
int i;
for (i=0;i<5; i++)
{
int h;
printf("%p \n",&h);
}
return 0;
}

每次循环的输出都是一样的。如其他问题所述For-loop Local Variables in C , Why each time a same address is allocated for the variable in local scope?这是由于编译器优化而发生的。我想找到一种方法来防止这种优化,以便每次声明变量 h 时都有不同的地址。我知道我可以使用 malloc 并每次分配不同的堆内存,但我想找到使用堆栈内存的解决方案。 gcc 是否有禁用此优化的标志?

最佳答案

您不能指望对编译器施加那种控制。它有权将您的变量放在任何它喜欢的地方。

如果您需要多个变量,请使用数组。

int h[5];
for (int i=0; i<5; i++)
{
printf("%p \n",&h[i]);
}

正如 Pascal 在评论中敏锐地指出的那样,您提出的功能将导致堆栈溢出。我确定你不想要那个。

关于c - 如何防止编译器在循环中对变量使用相同的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21665380/

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