【问题标题】:Dereferencing pointer to incomplete type error for a structure member取消引用指向结构成员的不完整类型错误的指针
【发布时间】:2015-05-15 07:58:14
【问题描述】:

我检查了其他类似问题的问题,但没有一个解决方案适用于我的情况。

手头的问题是,我正在尝试使用此结构创建具有动态内存的堆栈:

struct stekas{
    int content;
    struct stekas *link;
} *top = NULL;

但是,我在一些函数中遇到了麻烦:具体来说,“取消引用指向不完整类型的指针”。这是错误的代码:

struct node *temp;
temp = (struct stekas*)malloc(sizeof(struct stekas));
/* some code */
temp = top;
printf("Popped out number: %d\n", temp->content);
top = top->link;
free(temp);

这是另一个得到错误的函数:

int i;
struct node *temp;
/* some code */
for (i = top; i >= 0; i--) {
printf("%d\n", temp->content[i]);

我假设它与指针未连接到内容有关。我检查了其他问题,他们似乎对结构本身有问题,但我个人认为这个问题没有任何问题。

【问题讨论】:

  • 标准警告:请do not cast malloc()C 中的家人的返回值。
  • 也许你想要printf("%d\n", (temp[i]).content); 而不是printf("%d\n", temp->content[i]);
  • 您似乎认为struct node 包含一个名为content 的int 数组,但您只向我们展示了struct steaks 的定义

标签: c arrays struct compiler-errors dynamic-memory-allocation


【解决方案1】:

看来这些代码sn-ps中使用的struct node

struct node *temp;
temp = (struct stekas*)malloc(sizeof(struct stekas));
/* some code */
temp = top;
printf("Popped out number: %d\n", temp->content);
top = top->link;
free(temp);

int i;
struct node *temp;
/* some code */
for (i = top; i >= 0; i--) {
printf("%d\n", temp->content[i]);

没有定义。

我想你的意思是struct stekas

另外两个代码 sn-ps 还有其他严重错误。例如,您分配了内存并将其地址分配给指针temp

temp = (struct stekas*)malloc(sizeof(struct stekas));
/* some code */

然后覆盖指针。所以分配的内存地址就丢失了。

temp = top;

所以有内存泄漏。

或在此声明中

for (i = top; i >= 0; i--) {

变量 i 具有 int 类型,而 top 是指针。所以这个赋值 i = top 和这个递减的 i-- 没有意义。

对 printf 语句中使用的表达式 temp->content[i] 有何看法?

printf("%d\n", temp->content[i]);

content 既不是指针也不是数组。所以你可能不会应用下标运算符。

【讨论】:

  • 我承认代码是一团糟,而且我遇到了更多问题,但对于我遇到的主要问题,取消引用,这解决了问题。谢谢。
  • @Anstane 我建议您在 SO 上就您的项目提出新的附加问题,因为它似乎包含其他问题。
  • Erm...我应该在编辑完主帖后在这里问问题,还是应该搜索然后问一个全新的问题?原谅我,我还是新手,不太了解适当的发帖礼仪。
  • @Anstane 提出一个新问题。这个问题已经回答了。
【解决方案2】:

我在这里看到的问题是

  1. struct node 未定义是它使用的范围。也许struct node 应该是struct stekas

  2. printf("%d\n", temp->content[i]);

    content 不是可以取消引用的数组指针

也就是说,

  • 通常最好在取消引用指针之前检查 NULL。
  • 确保你的free()分配的内存在temp = top;之前分配给temp,以避免内存泄漏。

另外,请do not castmalloc()的返回值和C中的家人。

【讨论】:

    【解决方案3】:
    temp = top;
    

    top 为 null 并且您正在使 temp 指向 null 并取消引用它,这将导致未定义的行为。

    malloc() 会给你内存,你可以访问它,所以使用它。

    【讨论】:

    • 两种情况下的剪切代码仅检查top = NULL是否为空,如果是,则表示堆栈为空。
    • @Anstane 引用空指针会导致未定义的行为
    • 如果我错了请纠正我,但你提到的问题不应该导致编译器错误。
    猜你喜欢
    • 2014-07-06
    • 2014-05-09
    • 2016-07-12
    • 2021-07-25
    • 1970-01-01
    • 2017-02-24
    • 2011-04-06
    相关资源
    最近更新 更多