【问题标题】:Why does iterable pointer become NULL?为什么可迭代指针变为NULL?
【发布时间】: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_itemiterable 参数应该相等 - 但 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-&gt;iterable, void*, "%p");
  • 我觉得不错:ideone.com/QvRwjn
  • 我刚刚编译并运行了你的代码。它运行良好,“可迭代”不为空。我使用的是 linux 和 gcc 4.7,所以也许问题出在你的编译器上?
  • 我也在调试器中运行了代码。由于它在其他编译器中运行良好,我会检查它是否只是我的编译器。

标签: c pointers


【解决方案1】:

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

您的编译器将无法正确编译以下代码。断言应该被保留,但 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);
}

【讨论】:

    【解决方案2】:

    我能想到的唯一可能的解决方案是更新您的编译器或获得一个新的。

    【讨论】:

    • 不确定为什么要编辑此答案;它原本是清晰、简洁和正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 2011-08-22
    • 1970-01-01
    • 2010-10-16
    • 2021-09-29
    相关资源
    最近更新 更多