0

I have the following struct defined with the typedef keyword:

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

It gives me the following error when compiling:

error: unknown type name ‘NODE’ I looked it up, and found this stack overflow post, which said I should change it to

typedef struct n{
  int data;
  n *next;
}NODE;

I have two question about this.

First, what is the n? I thought NODE was the name of the struct, so is that a second name?

The second is, why can I put the n as a data type, but not NODE?

  • 1
    Does this answer your question? [typedef struct vs struct definitions](https://stackoverflow.com/questions/1675351/typedef-struct-vs-struct-definitions) – underscore_d Mar 11 '21 at 16:53
  • Even if it's related, it doens't answer my questions directly, no –  Mar 11 '21 at 16:56

2 Answers2

1

NODE is not the name of the struct. It's a typedef, i.e. an alias for the struct. In the first case, the struct is unnamed. In the second case, the struct is named struct n.

The reason you can't use NODE inside of the struct is because that name hasn't been defined yet at the time it is used. So you need to use the actual name of the struct (which is defined) in order to create a pointer to it.

Also note that the struct keyword is required in C when using the struct's name, i.e.:

struct n *next;
dbush
  • 205,898
  • 23
  • 218
  • 273
0

With your combined structure definition and typedef, the name NODE is not yet defined at the location when you try to use it.

typedef struct{
  int data;
  NODE *next; // name NODE used here
}NODE;        // name NODE defined here

You can do the typedef before the structure definition to use it for a pointer.

typedef struct n NODE; // NODE defined as incomplete type

struct n {
  int data;
  NODE *next; // use as pointer is OK
}; 
// from here NODE is completely defined

But you cannot define a variable or structure field of type NODE before the structure is really defined.

typedef struct n NODE;

#if 0
// does not work because NODE is an incomplete type here
struct wrapper {
  NODE node;
};
#endif

// using a pointer to an incomplete type is OK
struct n {
  int data;
  NODE *next;
}; 

// works
struct wrapper {
  NODE node;
};

You can use

typedef struct n{ // type "struct n" known here
  int data;
  struct n *next; // use known type
}NODE; // type alias NODE known here

because the type struct n is already known when you use it for the pointer.

Note that in C you have to use struct n *next (in contrast to C++).

Bodo
  • 9,287
  • 1
  • 13
  • 29