For a testing assignment I am supposed to detect errors in the following C program:
#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:
Assignment from incompatible pointer type [Wincompatible-pointer-types]
at the statements 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. Help much appreciated.
typedef struct {
struct chain *next;
int contents;
} chain;
this creates an anonymous structure chain
. But the next
pointer is of type struct chain*
. But there's no type struct chain
defined in your code at all! So the compiler can't know the relationship between the type chain
and struct chain
.
You can instead name the struct:
typedef struct chain {
struct chain *next;
int contents;
} chain;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.