Reputation: 21
I'm having a hard time understanding the typedefs in this C structure.
typedef struct node {
int value;
list rest;
} node;
typedef struct node *list;
What's the difference between the "node" typedef declaration and the "list" declaration? Why is list prefaced as a pointer? Isn't "node" a pointer as well? Why can't I simply say "typedef struct node list" and omit the asterisk? I've been searching everywhere and I can't really find a satisfactory answer.
Upvotes: 2
Views: 456
Reputation: 126957
The first typedef
defines node
as an alias for struct node
, to allow you to refer to it simply as node
without writing struct node
every time (in C "regular" type names and struct
names live in two different namespaces). It's equivalent to:
struct node
{
int value;
struct node* rest;
};
typedef struct node node;
The second typedef
, instead, defines list
as an alias for node *
, i.e. defines the type list
as a pointer to a node
structure.
(by the way, personally I find that this is very bad style: hiding pointers inside typedef
s is almost always a bad idea; one can argue that a pointer to the first element in a list could be identified as the list, but the usage of list
even for the rest
pointer is IMHO not very nice)
Upvotes: 5
Reputation: 14034
node
is a struct
, which is (confusingly) named the same thing as struct node
. list
is a pointer to struct node
. So the following are equivalent:
struct node *a;
node *a;
list a;
Upvotes: 1
Reputation: 213200
node
is just a synonym for struct node
list
is a pointer to a struct node
(or node
)
Each node instance contains a list
pointer which enables you to build data structures such as (singly) linked lists, etc.
Upvotes: 0
Reputation: 57804
The first declaration says that a node
is the structure. The second says that a list
is a pointer to a node.
So, this would be proper code using those declarations:
list x;
node n;
x = &n;
Declaring an item using typedef struct node list
is not correct. The typedef
statement declares a new type. The keyword typedef
is not part of the type's name.
Upvotes: 1
Reputation: 124790
node
is not a pointer; it is a struct
. list
is a typedef for a pointer to node
.
You typedef
a struct
in C to avoid typing struct node ...
everywhere.
Whether or not this is good practice is questionable (most will agree that hiding a pointer type behind a typedef
, unless it is truly opaque, is a bad idea), but that's the gist of it.
Upvotes: 1