【问题标题】:Error Traverse List of LinkedList in CC中LinkedList的错误遍历列表
【发布时间】:2017-10-14 05:07:04
【问题描述】:

我编写了以下代码,但是当我尝试编译代码时,编译器显示以下错误。我的错在哪里?

编译器错误:

main.c:32:39:错误:取消引用指向不完整类型“结构信息”的指针 printf("信息:%d\n", ptr->_number);

#include <stdio.h>
#include <stdlib.h>

typedef struct Informaion{
    int _number;
    struct Informaion *next;
} Information;

int main(int argc, char const *argv[]){

    Information *temp;
    Information *head;

    temp = malloc(sizeof(Information));
    temp->_number = 20;
    head = temp;

    temp = malloc(sizeof(Information));
    temp->_number = 21;
    head->next = temp;

    temp = malloc(sizeof(Information));
    temp->_number = 22;
    head->next->next = temp;

    temp = malloc(sizeof(Information));
    temp->_number = 23;
    head->next->next->next = NULL;

    struct Information *ptr = head;
    while(ptr != NULL) {
      printf("Information : %d\n", ptr->_number);
      ptr = ptr->next;
   }

    free(head);
    free(temp);
    return 0;
}

【问题讨论】:

  • 你的结构中有很多印刷错误。我不知道您要做什么,因为您没有说出来,但是如果您想打印地址,请使用%p 而不是%d
  • 我想显示我为结构设置的数据。我修好了。
  • @MikhailRazborov 如果您的问题得到解决,您可以接受一个答案。
  • 在调用任何堆分配函数时:(malloc, calloc, realloc),始终检查 (!=NULL) 返回值以确保操作成功
  • 不使用main()的参数时,使用备用签名:int main( void )

标签: c compiler-errors singly-linked-list dereference


【解决方案1】:

您的类型名称是struct Informaion。在您正在使用的行中

struct Information *ptr = head;

要解决这个问题,您可以修复错字,也可以直接通过 typedef 使用它。

Information *ptr = head;

作为一般惯例,您不应使用以下划线开头的变量或任何标识符。这些是为编译器保留的。建议你把_number换成别的。

【讨论】:

    【解决方案2】:

    结构定义有错别字

    typedef struct Informaion{
                         ^^^  
        int _number;
        struct Informaion *next;
    } Information;
    

    因此,请在声明的下方各处使用类型说明符 struct Informaion 或 Information。

    这段代码sn-p

    temp = malloc(sizeof(Information));
    temp->_number = 23;
    head->next->next->next = NULL;
    

    没有意义。其地址存储在指针 temp 中的已分配对象不会添加到列表中。

    这样写就对了

    temp = malloc(sizeof(Information));
    temp->_number = 23;
    head->next->next->next = temp;
    head->next->next->next->next = NULL;
    

    要释放分配的节点,您应该编写

    for ( Information *ptr = head; head != NULL; ptr = head) {
      head = head->next;
      free( ptr );
    }
    

    【讨论】:

      【解决方案3】:

      换行:

      struct Information *ptr = head;
      

      到:

      struct Informaion *ptr = head;  //no t 
      

      或:

      Information *ptr = head;
      

      错误就会消失。您可以定义的类型可以使用struct Informaion 或Information 命名,就像您使用typedefed 一样。


      注意不鼓励使用以下划线开头的变量(例如您的_number 变量),因为编译器会使用这些名称。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多