c - 使用 malloc 初始化指向结构体的指针

标签 c pointers linked-list

这可能是一个非常简单的解决方案的问题,但我无法理解它...我正在尝试使用结构为学校项目实现链表,但是当我初始化第一个节点时,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/

相关文章:

c++ - 基本 OpenGL 程序崩溃,但适用于 gdb

c++ - 如何在 C++ 中删除这个二维动态数组

C错误: Initialization From Incompatible Pointer Type

c++ - 在 C++ 中,我可以为运算符重置函数指针吗?

c++ - 在 C++ 中将字节数组转换为 unsigned long

java - 方法的空指针异常

python - 删除 Python 双链表中的节点时遇到问题

c - 忽略 C 程序输入中的 # 注释

计算距离(毫米)的坐标

c - 使用 freeRTOS 队列 API 在 freeRTOS 应用程序中创建队列更好,还是使用自定义数据结构更好?