Related List Implementation in C with structure

I use this structure as a linked list:

 typedef struct Node{
       int value;
       struct node_t* next;

 }node_t;

And everything works fine until I put it struct node_t* nextin front of the field int value, then I have a lot of garbage values ​​working with this structure. Is it about the wrong implementation or something else in the code?

+4
source share
3 answers

You invoke your structure Nodeand determine the type node_t. Then you use node_tit as if it were the name of a structure, not a type.

try it

typedef struct node {
    int value;
    struct node *next;
} Node;

or

typedef struct node Node;
struct node {
    int value;
    Node *node;
};

If you call it struct Node, then

struct Node {
    int value;
    /* The compiler doesn't know what `struct Node' is yet */
    struct Node *next;
    /* But you can always declare pointers, even of types the compiler
     * doesn't know everything about. Because the size of a pointer
     * does not depend on the type of the pointee.
     */
};

. typedef - , , , struct. typedef ing , ,

typedef struct Node node;

Node ( , Node IS A TYPE),

node *anode;

-

struct node *anode;

, struct Node, struct Node.

, node_t ,

struct node_t *next;

, , ,

typedef struct Node node_t

- struct node_t, node_t struct , , , struct Node.

- , . struct Something, Something. , , , , Something struct.

. Node, , _t. , , , , _t . , , , . struct.

+4

node_t. , struct Node , . , typedefs , struct .

/* This is correct */
typedef struct Node
{
    int x;
    struct Node *next;
} node_t;

/* while these are incorrect */

/* Prefixing struct keyword to a typedef'ed type */
struct node_t *listhead;

/* The type is inclomplete and you are using an alias of the type
   which doesn't even exist */
typedef struct Node
{
    int x;
    node_t *next;
};
+1

You are trying to create a pointer to a structure that you have not created yet. So it should have been

typedef struct Node{
int value;
struct Node* next;
}node_t;
+1
source

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


All Articles