【问题标题】:why value of head changes in main and in function?为什么 head 的值在 main 和 function 中发生变化?
【发布时间】:2021-08-07 01:46:14
【问题描述】:

头指针指向函数和main中的不同节点。为什么?

#include<stdio.h>

#include<stdlib.h>

      struct node{

    int data;

    struct node *link;

};

int insert_node(struct node *head){

    struct node *ptr=(struct node*)malloc(sizeof(struct node));

    struct node *temp=(struct node*)malloc(sizeof(struct node));

    ptr->data=12;
    ptr->link=NULL;
    ptr->link=head;
    head=ptr;
    temp=head;
    while(temp!=NULL){
            printf("\n%d",temp->data);
            temp=temp->link;
    }
    printf("\nHead in fn=:%d",head);
}

int main(){


    struct node *head=(struct node*)malloc(sizeof(struct node));
    head->data=56;


    struct node *current=(struct node*)malloc(sizeof(struct node));
    current->data=78;

    head->link=current;

    struct node *current1=(struct node*)malloc(sizeof(struct node));
    current1->data=45;

    current->link=current1;


    struct node *current2=(struct node*)malloc(sizeof(struct node));
    current2->data=69;
    current2->link=NULL;
    current1->link=current2;
    insert_node(head);
    printf("\nhead in main-:%d",head);



    return 0;
}

https://i.stack.imgur.com/KudzR.png

【问题讨论】:

  • 你设置head=ptr; ....

标签: c linked-list


【解决方案1】:

C 中函数的参数是所传递内容的副本。修改被调用函数中的参数不会影响调用者传递的内容。

在这种情况下,insert_node 函数将一个新值分配给head 并打印出来。更改不会影响main 函数中的head,原始值会打印在main 中。

还请注意,您通过将错误类型的数据传递给printf() 来调用未定义的行为%d 用于打印int。要通过printf() 打印指针,您应该将它们转换为void* 并使用%p

【讨论】:

  • 那么我应该怎么做才能修复代码?
  • insert_node 告诉调用者head 的新值。可以通过返回新值或接收指向struct node* 的指针并将新值写入指针指向的位置来完成。
猜你喜欢
  • 2020-09-30
  • 2016-01-09
  • 2018-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多