【问题标题】:Linked list syntax链表语法
【发布时间】:2012-09-17 10:41:26
【问题描述】:
typedef struct  {
 char name [25] ;
 char breed [25] ;
 int age  ; 
 struct animal *next ;
 } animal ;

 animal *ptr1 , *ptr2 , *prior ;
 ptr1 = (animal*)malloc( sizeof (animal) ) ;
 strcpy ( (*ptr1).name , "General" ) ;
 strcpy ( (*ptr1).breed , "Foreign breed" ) ;
 (*ptr1).age = 8 ;


 (*ptr1).next = NULL ;
 prior =ptr1 ;
 printf ("%s\n" , (*prior).name ) ;
 printf ("%s\n" , (*prior).breed ) ;
 printf ("%d\n" , (*prior).age ) ;
 printf ("%p\n" , (*prior).next ) ;
 free (ptr1) ;
 ptr1 = (animal*)malloc( sizeof (animal) ) ;
 strcpy ( (*ptr1).name , "General 1" ) ;
 strcpy ( (*ptr1).breed , "Abroad breed" ) ;
 (*ptr1).age = 24 ;
 (*ptr1).next = NULL ;
 (*prior).next = ptr1 ;

这是绘制链表的代码。 整个代码执行时在最后一行显示错误:

在函数'main'中: 警告:来自不兼容指针类型的赋值[默认启用]

【问题讨论】:

  • 如果您指出 在哪里 会出现错误,这可能会有所帮助。由于它是一个编译错误(即不是您的程序错误,而是编译器关于您的代码的某些问题的错误),因此错误消息包含一个行号。今后,请发布所有条完整且未经编辑的消息。
  • 请注意,在最后一行中,prior 指向的是先前释放的内存区域;这可能会导致您的程序崩溃
  • 另外,为什么使用例如(*ptr1).next 而不是更普通的ptr1->next?
  • 新用户提示:提出问题总是好的,不要假设人们会确切地知道你想知道什么。报告错误消息时,您可以说明生成它的编译器版本。

标签: c list linked-list


【解决方案1】:

把你的结构定义改成这个

typdef struct Animal_
{
  char name [25];
  char breed [25];
  int age; 
  struct Animal_* next;
} Animal;

没有Animal_,结构是匿名结构,不能有指向它的指针。

【讨论】:

  • 完全不需要下划线。
【解决方案2】:

将您的声明更改为:

typedef struct animal {
    char name [25] ;
    char breed [25] ;
    int age;
    struct animal *next;
 } animal;

结构标记animal 已添加到声明中。 您现在拥有animal 类型,struct animal 的别名。

【讨论】:

    【解决方案3】:

    “标签”名称空间(struct 之后的名称)和标识符名称空间(例如,您使用 typedef 声明的名称空间)在 C 中是不同的。

    我发现最简单的方法是始终一次性转发声明 struct 标记和 typedef

    typedef struct animal animal;
    

    从那时起,即使在 struct 的声明中,您也可以轻松使用 typedef 名称:

    struct animal {
      ....
      animal* next;
    };
    

    【讨论】:

    • 您的帮助和迭代使我顺利通过..谢谢大家。
    • @sauravverma,如果答案对您有帮助,请投票,然后选择真正回答您问题的答案并“接受”它。
    【解决方案4】:

    animal 是 typedef 的名称,而不是结构的名称。试试这个:

    typedef struct _animal {
        char name [25];
        char breed [25];
        int age; 
        struct _animal *next;
    } animal;
    

    【讨论】:

    • 您永远不应该使用带有前导下划线的全局名称,因为它们是保留的。
    • 在这种情况下,您甚至不需要下划线,typedef struct animal { ... } animal; 完全有效。
    【解决方案5】:

    这实际上是一个警告,而不是错误。 我不明白你为什么使用 (*s).m 而不是 s->m。它更简单,更自然。 我没有在您的代码中看到函数 main 以及出现错误的行,我想除了结构声明之外的所有代码都是函数 main。 尝试像这样声明您的结构(您可能还需要添加“typedef struct animal”,具体取决于您的编译器): 结构动物{ ... 动物 *下一个; };

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      相关资源
      最近更新 更多