如何在C中为链表的头部分配space?
How to allocate space for the head of linked list in C?
struct node {
int data;
struct node *next;
};
int main() {
struct node *head = malloc(sizeof(struct node));
struct node *current = head;
...
};
虽然这段代码可以 运行 没有任何警告或错误,但 Valgrind 会给出一些消息说 Conditional jump or move depends on uninitialised value(s)
、Uninitialised value was created by a heap allocation
我不知道出了什么问题。我们在 main
函数之外定义了一个 node
结构。所以我认为我们可以使用 sizeof(struct node)
,不是吗?
您需要用头初始化数据和下一个指针。我是说
head->data = 0;
head->next = NULL;
它将通过 Valgrind 检查
struct node {
int data;
struct node *next;
};
int main() {
struct node *head = malloc(sizeof(struct node));
struct node *current = head;
...
};
虽然这段代码可以 运行 没有任何警告或错误,但 Valgrind 会给出一些消息说 Conditional jump or move depends on uninitialised value(s)
、Uninitialised value was created by a heap allocation
我不知道出了什么问题。我们在 main
函数之外定义了一个 node
结构。所以我认为我们可以使用 sizeof(struct node)
,不是吗?
您需要用头初始化数据和下一个指针。我是说
head->data = 0;
head->next = NULL;
它将通过 Valgrind 检查