A few days ago I made a function, which worked just fine. This is struct defining I used.
typedef struct {
int data;
struct Node * next;
} Node;
typedef struct {
Node * head;
Node * current;
int size;
} List;
Then I have this function
void returnMiddle(List * list){
Node * first = list->head;
Node * second = list->head;
if(list->head != NULL){
while(second != NULL && second->next != NULL){
first = first->next;
second = first->next->next;
}
printf("Middle is: %d", first->data);
}
}
But now I receive given error and I don't understand why? Does anyone know?
second = first->next->next;
<<< this is where I get an error message, up to here it works fine
In this typedef declaration of a structure
typedef struct {
int data;
struct Node * next;
} Node;
the type struct Node
is an incomplete type. That is the type name struct Node
is introduced but not defined.
Pay attention that the typedef name Node and the type name struct Node name two different entities. The name Node
names an unnamed structure while struct Node
names a not yet defined structure.
It is obvious that you mean the following
typedef struct Node {
int data;
struct Node * next;
} Node;
error: dereferencing pointer to incomplete type
This means that the compiler couldn't find a definition of the struct within the translation unit where you made that access - it could only find a declaration. struct Node * next;
is as it turns out, a pointer to a type that wasn't previously defined at the point where you declared it. Because it only becomes defined when the compiler reaches the };
of the struct.
For a self-referencing struct, you need to forward-declare the type in order to use it as a struct member. Depending on your coding style that either means:
typedef struct Node Node;
struct Node {
int data;
struct Node* next; // also possible: Node* next;
};
or
typedef struct Node {
int data;
struct Node* next;
} Node;
(The type Node
and the struct tag Node
actually live in separate namespaces, but this is one of those things one need not ponder about - just do.)
struct Node * next;
struct Node
is a forward declaration to structure Node
, but you haven´t defined a structure called Node
yet - means struct Node
is an incomplete type.
typedef struct {
...
} Node;
Node
is a typedef for the structure definition. it is not equal to struct Node
.
Provide the structure tag Node
:
typedef struct Node {
int data;
struct Node * next;
} Node;
and your code works fine.
Also have a look at here:
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.