链接列表语法

时间:2012-09-17 10:41:26

标签: c list linked-list

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'中:   警告:从不兼容的指针类型[默认启用]

进行分配

5 个答案:

答案 0 :(得分:1)

将结构定义更改为此

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

如果没有Animal_,struct就是一个匿名结构,并且没有指向它的指针。

答案 1 :(得分:1)

将您的声明更改为:

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

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

我发现,最简单的方法是始终向前一步声明struct标记和typedef

typedef struct animal animal;

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

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

答案 4 :(得分:0)

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