c - 结构通过引用问题

标签 c

<分区>

我在用 C 语言初始化节点值以传递指针时遇到问题,

我已经写了类似 follow 的东西,

#include<stdio.h>
#include<stdlib.h>
struct node{
    int data;
    struct node *next;
};

void add(struct node *head, int val){
    struct node *n1 = NULL;
    n1 = (struct node *)malloc(sizeof(struct node ));
    n1 -> data = val;
    n1 -> next = NULL;

    if(head == NULL){
        head = n1;
        printf("Head2 is initialized");
        return;
    }
}


int main(){
    struct node *ptr = NULL;
    struct node *temp;
    add(ptr, 11);
    printf("\nData = %d", ptr->data);
    return 0;
}

你能告诉我这段代码有什么问题吗,

当我执行

printf("\nData = %d", ptr->data);

系统显示 Windows 已停止工作

谢谢

最佳答案

简答:如果你想改变指针指向的值,你必须将指针传递给指针:

void add(struct node **head, int val) {
   ...
    if(*head == NULL){
       *head = n1
}

int main(){
   ...
    add(&ptr, 11)
   ...
}

长答案:当你在 main 中调用 add(ptr, 11) 时,你传递了一个内存地址和一个数字。内存地址和数字都是按值传递的。结果,对这些变量的更改都是局部的

在您的 add 方法中 - 当您在 head = n1 中为 head 赋值时,您更改了局部变量的值以指向新的内存地址。当您的函数返回时,更改消失了,因此 main 永远不会看到赋值并且 ptr 保持为 NULL。

如果你传递一个指向 ptr 的指针 - &ptr,你将传递内存中的一个位置,ptr 的值(内存地址)驻留在 main 中,所以当你调用 * head = n1* 你写n1的地址`这个位置的值会改变,main会看到。

另见 this question

关于c - 结构通过引用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31769701/

相关文章:

c中的char到int转换错误

c - sdcc 不接受代码

c - 提示用户输入后获取 "Segmentation fault (core dumped)"

c - 超过 50 万个元素的快速排序崩溃

c - 如何查找 B 树的层数

c - GPRBuild 不编译 C 文件

c - 在 char 指针数组中存储字符串的错误

c - 带有 icd 指针的 C 代码中的 Valgrind 错误

c - (C) 代码不能在所有需要的条件下工作

c - 如何从信号编号中获取人类可读的描述?