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.
Try sizeof(struct Node)
instead.
struct Node
应该用来指结构。如果您希望上面的代码有效,另一种方法是typedef
将struct Node
结构设置为
typedef struct Node {
int value;
struct Node *next;
} Node;