You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何传递struct node*指针给函数后,main函数中未体现修改?

问题分析与解决

你的代码里修改头结点后main函数未生效的核心原因是:C语言采用值传递机制,哪怕传递的是指针,也只是传递了指针变量的副本,函数内部对副本的修改不会影响main里的原指针变量。

具体代码分析

  • main函数中,head指向one结点(存储值11)。调用insertAtBeginning(head)时,会把head的当前值(即one的内存地址)复制一份给函数的形参head。
  • 函数内部创建了新结点temp,并把形参head指向这个新结点,但这只是修改了副本指针的指向,main里的原head变量依然指向原来的one结点,所以最终打印的还是11。

两种可行的修正方案

方案1:传递指针的指针

通过传递指针的地址(即指针的指针),让函数能够直接修改原指针变量的指向:

#include <stdio.h>
#include <stdlib.h>

typedef struct node* Node;

struct node{
    int a;
    struct node* next;
};

void insertAtBeginning(Node* head){
    Node temp = malloc(sizeof(struct node));
    temp->a = 10;
    temp->next = *head;
    *head = temp; // 解引用修改原指针的指向
}

int main(){
    Node one = malloc(sizeof(struct node));
    one->a = 11;
    Node head = one;
    insertAtBeginning(&head); // 传递指针的地址
    printf("%d", head->a); // 输出10
}

方案2:让函数返回新的头结点

修改函数为返回新的头结点指针,在main中用返回值更新原head变量:

#include <stdio.h>
#include <stdlib.h>

typedef struct node* Node;

struct node{
    int a;
    struct node* next;
};

Node insertAtBeginning(Node head){
    Node temp = malloc(sizeof(struct node));
    temp->a = 10;
    temp->next = head;
    return temp; // 返回新创建的头结点
}

int main(){
    Node one = malloc(sizeof(struct node));
    one->a = 11;
    Node head = one;
    head = insertAtBeginning(head); // 用返回值更新head
    printf("%d", head->a); // 输出10
}

内容的提问来源于stack exchange,提问作者Thirumal R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 08:27:21