这可能是一个非常简单的解决方案的问题,但我无法理解它...我正在尝试使用结构为学校项目实现链表,但是当我初始化第一个节点时,malloc似乎没有任何效果
到目前为止,这是我的代码:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
typedef struct Node Node;
struct Node
{
int data;
Node *next;
};
void init_List(Node *head, int data)
{
head = (Node*)malloc(sizeof(Node));
if(head == NULL)
{
printf("Memory Allocation Error");
return;
}
head->data = data;
head->next = NULL;
}
int main()
{
Node *head = NULL;
int N;
printf("N: ");
scanf("%d", &N);
init_List(head, N);
printf("%d", head->data);
}
无论我读取什么数字,以使节点的第一个数据打印为 cero。不知道会发生什么。 感谢您的帮助!
最佳答案
当您将 head
传递给函数 init_List
时,会创建 head
的本地副本,然后将内存分配给该本地指针。在main
中,head
仍然指向NULL
。
您需要在函数参数中使用指向指针的指针。
void init_List(Node **head, int data)
{
*head = malloc(sizeof(Node));
if(*head == NULL)
{
printf("Memory Allocation Error");
return;
}
(*head)->data = data;
(*head)->next = NULL;
}
你的函数调用应该像
init_List(&head, N);
另请注意,不要转换 malloc
的返回值。
关于c - 使用 malloc 初始化指向结构体的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30967744/