user1710702
user1710702

Reputation: 173

Unable to get this data structure to work (newbie)

I'm pretty new to C, and I've been trying to make a program with this data structure:

struct node {
    char command[100];
    char prereq[100][80];
    char *targ;
    int isUpdated;
} Node;

However, whenever I try to implement it in the code, like this:

Node n = malloc(sizeof(*n));

I get compiler errors such as "nmake.c:13:31: error: unknown type name ‘Node’".

I've tried code such as:

typedef struct node *Node;

with similar results. What's wrong?

Upvotes: 2

Views: 122

Answers (2)

rodrigo
rodrigo

Reputation: 98348

I think you are confused about what typedef does.

A declaration such as this one:

struct node { ... };

will define a type named struct node. Do not forget the word struct! If you say just node it will mean nothing (note that this is different in C++).

So now to create a local variable you do:

struct node x;

And to do a dynamic one:

struct node *px = malloc(sizeof(struct node));

Now, if you want to make an alias to the type, you use the same exact syntax than to create a variable, but you write typedef at the beginning of the declaration:

typedef struct node Node;

Or if you prefer the pointer type:

typedef struct node *PNode;

Then to create variables:

Node a;
Node *b = malloc(sizeof(Node));
PNode c = malloc(sizeof(Node)); //do not use sizeof(PNode) as it is useless here

Some people, as @WhozCraig says in the comments, and you seem to intend in the original code prefer to use the declaring variable for sizeof instead of the type:

Node *b = malloc(sizeof(*b));
PNode c = malloc(sizeof(*c));

Actually there is no real difference, other than the style, so pick your favorite!

Note that when defining the original struct you can use the same declaration to create variables or typedefs, but not both:

struct node { ... } a; //a is a variable

typedef struct node {...} b; //b is a type

Some people like to force the syntax and do something like this:

typedef struct node {...} Node, *PNode; //tree types in one line!

but personally I find this practice a bit dumb: don't typedef a pointer unless you want to hide the fact that it is a pointer.

Upvotes: 2

stdcall
stdcall

Reputation: 28880

What you probably want is:

typedef struct _node {
    char command[100];
    char prereq[100][80];
    char *targ;
    int isUpdated;
} Node;

/*
 * This defines a structure named _node.
 * To use it, you must add struct everytime, for instance:
 * struct _node foo;
 *
 * It also defines a typedef named Node which is a synonym to struct _node - Node
 */ 

Node *n = malloc(sizeof(*n));
/*
 * Because we want to dynamically allocate we need a pointer, so we declared it as a Node *
 */

Upvotes: 1

Related Questions