gpt4 book ai didi

c - 为什么可迭代指针变为NULL?

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

在这段代码中:

#include <stdio.h>

struct iter_obj
{
void *iterable;
};

#define new_iter_obj(iter) {iter}

void *array_item(int index, void *iterable)
{
if (index < 10)
{
return (void *) &(((int *) iterable)[index]);
}
else
{
return NULL;
}
}

void iterate(struct iter_obj *obj)
{
void *tmp;
int index = 0;

while ((tmp = array_item(index, obj->iterable)) != NULL)
{
printf("%d\n", *((int *) tmp));
index++;
}
}

int main()
{
int countdown[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
struct iter_obj cd_iter = new_iter_obj((void *) countdown);

iterate(&cd_iter);
}

输出应该是:

10
9
8
7
6
5
4
3
2
1

但是:没有输出。

问题是,main 中的倒计时数组和 array_itemiterable 参数应该相等 - 而且 iterable 最终为 NULL(我通过我的代码 使用适当的调试器散布调试宏发现了这一点。我在调试时没有发现我的代码有任何错误 - 看起来好像这几乎是随机的。

如果我更改代码以便直接传递 iterable 而不是通过结构传递,则指针保持不变(正确输出)。

这是为什么呢?它是 C99 的一部分,是 lcc buggy,还是什么?

我在 Windows 8.1 上使用 lcc-win32 3.8 (C99)。

新更新

我发现我的代码在 Pelles C 8.00 RC1 中工作正常。

最佳答案

你应该得到一个新的编译器。

您的编译器将无法正确编译以下代码。断言应该成立,但 lcc 有 cd_iter.iterable == NULL

#include <stdio.h>
#include <assert.h>

struct iter_obj
{
int *iterable;
};

int main()
{
int countdown[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
struct iter_obj cd_iter = { countdown };

assert(cd_iter.iterable == countdown);
}

关于c - 为什么可迭代指针变为NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22730947/

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