gpt4 book ai didi

C:自动存储类数组?

转载 作者:太空狗 更新时间:2023-10-29 14:50:53 25 4
gpt4 key购买 nike

我正在阅读C How to Program,我对数组的存储类有疑问。书中说:

Array and structs are "static" entities in that they remain the same size throughout the program execution (they may, of course, be of automatic storage class and hence created and destroyed each time the blocks in which they're defined are entered and exited)

我不确定 block 是什么意思,我目前的理解是函数/for/while 是 block 。我尝试了以下方法:

...
for (size_t i=1; i<=2; i++) {
printf("round %c:", i+'0');
int a[10];
show_array(a, 10); // this is a function that prints all elements of `a`.
for (size_t j=0;j<10;j++) {
a[j]=8;
}
}

我得到了输出:

round 1:0,0,0,0,-1160480784,22023,-1160481168,22023,1594487680,32766,
round 2:8,8,8,8,8,8,8,8,8,8,

int a[10] 似乎是静态的,而不是自动存储类,我是不是漏掉了什么? (我理解的四个存储类)

我用了ideone.com运行我的测试,如果你需要这些信息。

最佳答案

你确实错过了一些东西。 a 确实有自动存储,打印的值是内存被重新使用的结果,不是存储是持久的。这些值将在 Debug模式下重置(可能不是所有开发环境都会重置这些值,但有些会在每次迭代时将成员设置为 0xCCCCCCCC )。此外,好的编译器(大多数编译器,如果你启用所有警告)会告诉你你在这里使用未初始化的数据。

如果你还是不相信我,试试这个例子。它将显示 a 中的内存值被存储在 b 中的值覆盖。数组 aif 语句的依赖代码块的末尾不再存在,并且所有内存都可供系统使用。在下一次迭代中,它可能会用于数组 b,这就是为什么您会在数组 b 中看到值 8 的原因,即使它们已分配给 一个

for (size_t i=1; i<=2; i++)
{
if( i&1 )
{
printf("round %c:", i+'0');
int a[10];
show_array(a, 10);
for (size_t j=0;j<10;j++) a[j]=8;
}
else
{
printf("round %c:", i+'0');
int b[10];
show_array(b, 10);
for (size_t j=0;j<10;j++) b[j]=888;
}
}

为了最终确认内存正在被重新使用,您可以修改 show_array 以打印传入的原始指针,而不仅仅是单个元素。您应该每次都看到相同的地址。

关于C:自动存储类数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53382014/

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