【发布时间】: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