[英]Assignment from incompatible pointer type[Wincompatible-pointer-types]
For a testing assignment I am supposed to detect errors in the following C program:对于测试任务,我应该检测以下 C 程序中的错误:
#include <stdlib.h>
#include <stdio.h>
typedef struct {
struct chain *next;
int contents; } chain;
int main() {
int index;
chain *list;
chain *p;
chain *pointer;
list = malloc(sizeof(chain));
p = list;
for(index=0;index<10;index++) {
(*p).contents = index;
(*p).next = malloc(sizeof(chain));
p = (*p).next;
} ;
p = pointer = list;
index = 0;
while (index < 9) {
printf("cell # %d: %d\n",index,(*p).contents);
p = (*p).next;
free(pointer);
pointer = p;
index++;
} ;
printf("First cell: %d\n",(*list).contents);
return 0;
}
I get the following 2 errors:我收到以下 2 个错误:
Assignment from incompatible pointer type [Wincompatible-pointer-types]
at the statements p=(*p).next
.在语句p=(*p).next
。
I have a feeling this might be something trivial, but I am a complete novice at C and can't figure out the correct syntax for these statements.我有一种感觉,这可能是微不足道的,但我是 C 的新手,无法弄清楚这些语句的正确语法。 Help much appreciated.非常感谢帮助。
typedef struct {
struct chain *next;
int contents;
} chain;
this creates an anonymous structure chain
.这将创建一个匿名结构chain
。 But the next
pointer is of type struct chain*
.但是next
指针的类型是struct chain*
。 But there's no type struct chain
defined in your code at all!但是您的代码中根本没有定义类型struct chain
! So the compiler can't know the relationship between the type chain
and struct chain
.所以编译器无法知道 type chain
和struct chain
之间的关系。
You can instead name the struct:您可以改为命名结构:
typedef struct chain {
struct chain *next;
int contents;
} chain;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.