Why does typedef'ing throw an error with structs that have fields that refer to themselves?

I had a strange mistake trying to better understand the structure, and I would like to better understand it. I tried to create a small linked list without using malloc () and print one of them by accessing it through the .next field of the previous node and using β†’ notation.

I had the following code:

1 #include<stdio.h>
2 #include<stdlib.h>
3
4 int main(){
5
6     typedef struct {
7         int data;
8         struct node *next;
9     }node;
10
11     node m;
12     m.data = 350;
13     m.next = NULL;
14
15     node n;
16     n.data = 2;
17     n.next = &m;
18   
19     printf("%d %d \n", m.data, n.next->data);
20     return 0;
21
22 }

and I got the error message on line 17:

"warning: assignment from an incompatible pointer type [enabled by default] n.next = & m;"

and the error message on line 19:

": dereference pointer to an incomplete type printf ("% d% d \ n ", m.data, n.next-> data);

However, someone changed the code a bit and earned the code. Here is the functional code:

1 #include<stdio.h>
2 #include<stdlib.h>
3
4 int main(){
5
6     typedef struct nodey{
7         int data;
8         struct nodey *next;
9     }node;
10
11     node m;
12     m.data = 350;
13     m.next = NULL;
14
15     node n;
16     n.data = 2;
17     n.next = &m;
18    
19     printf("%d %d \n", m.data, n.next->data);
20     return 0;
21
22 }

, - , , & m typedef. , ?

+4
2

Typedefs structs . , struct.

 typedef struct {
     int data;
     struct node *next;
 }node;

node. , typdef node , struct node . , struct node, .

n.next = &m, node * struct node *, .

 typedef struct nodey{
     int data;
     struct nodey *next;
 }node;

struct nodey node struct nodey.

+3
typedef struct {
    int data;
    struct node *next;
}node;

-, struct node () , struct node, node. node?

-, typedef struct . , struct typedef. , typedef struct, :

typedef struct nodey node;

struct nodey {
    int data;
    node *next;
};

( , ++, struct class , .)

+2

Source: https://habr.com/ru/post/1655908/


All Articles