【发布时间】:2014-05-08 23:37:18
【问题描述】:
在这段代码中:
#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_item 的 iterable 参数应该相等 - 但 iterable 最终为 NULL(我通过我的代码洒调试宏发现了这一点并且使用适当的调试器。我在调试时没有发现我的代码有任何问题——这似乎是非常随机的。
如果我更改代码以便直接传递 iterable 而不是通过结构,则指针保持不变(正确输出)。
这是为什么呢?它是 C99 的一部分,是 lcc 的错误,还是什么?
我在 Windows 8.1 上使用 lcc-win32 3.8 (C99)。
新更新
我发现我的代码在 Pelles C 8.00 RC1 中可以正常工作。
【问题讨论】:
-
为什么不在调试器中单步调试代码,看看到底发生了什么?
-
可以考虑调试
struct iter_obj成员的内容:debug_local_var(whatever->iterable, void*, "%p"); -
我觉得不错:ideone.com/QvRwjn
-
我刚刚编译并运行了你的代码。它运行良好,“可迭代”不为空。我使用的是 linux 和 gcc 4.7,所以也许问题出在你的编译器上?
-
我也在调试器中运行了代码。由于它在其他编译器中运行良好,我会检查它是否只是我的编译器。