0
4

3 回答 3

3

Welcome to SO and the wonderful world of C!

A few pointers for you:

Syntax-ically there's no problem with defining a struct inside a function, but typically it's defined outside so that it can be used in other functions. For example:

main(){ 
  struct nodedef{vars};
  add_to_node(node var);
}

add_to_node(node var)
{
   // How can I add a to a node when I don't know what that is?
}

The main problem with your code is that you aren't correctly referencing your node later on, if I declaire:

struct me {
    int i;
};

Then anytime I reference this type of struct, I have to explicitly say struct again:

struct me myself;
myself = malloc(sizeof(struct me));
myself.i = 5;

The way to avoid this reuse of the struct keyword is to use the typedef:

typedef struct me {
    int i;
}m;

m myself;
myself = malloc(sizeof(m));
myself.i = 5;

Last point is anytime you allocate some memory via malloc() make sure you call free() to release that memory:

free(myself); 

Or else you'll have a memory leak.

于 2012-12-03T16:13:10.173 回答
2

Try sizeof(struct Node) instead.

于 2012-12-03T15:45:00.507 回答
0

struct Node应该用来指结构。如果您希望上面的代码有效,另一种方法是typedefstruct Node结构设置为

typedef struct Node {
    int value;
    struct Node *next;
} Node;
于 2012-12-03T15:51:01.757 回答