【问题标题】:Start pointer not updating while passing by reference [duplicate]通过引用传递时开始指针不更新[重复]
【发布时间】:2017-02-06 13:48:51
【问题描述】:

这是推送功能。

void push(struct node **head)
{
    struct node *temp;
    temp = new node;
    cout<<"enter the value";
    cin>>temp->data;
    temp->link=NULL;
    if(*head==NULL)
    {   
        *head=new node;
        *head=temp;
    }
    else{
        temp->link=*head;
        *head=temp;
}
}    

这就是我所说的推送。

struct node *start=NULL;
push(&start);

这是节点

struct node{
    int data;
    struct node *link;
};

现在的问题是:我认为列表没有更新。开始始终保持为空。不知道为什么。

编辑:

void display(struct node **head)
{
    struct node *temp;
    temp=*head;
    if(*head==NULL){
        cout<<"\nthe head is NULL\n";
    }
    while(temp!=NULL)
    {
        cout<<temp->data;
        temp=temp->link;
    }

}

int main() {
    struct node *start=NULL;
    push(&start);
    push(&start);
    push(&start);
    push(&start);
    push(&start);
    display(&start);
    return 0; 
}

输入:

1

2

3

4

5

现在显示出来的应该是 5 4 3 2 1 但有一些错误。

【问题讨论】:

  • 如果只有一种方法可以避免使用指针模拟传递引用的 C 厌恶。如果只有 C++ 有 true 引用。这将是一个值得考虑的功能,是吗? :-)
  • 可能不是你的问题,但*head=new node; 是多余的。
  • minimal reproducible example 会增加答案的可能性和质量。
  • @SamarYadav 因为无论如何你都在下一行分配了temp。分配的内存泄露了。

标签: c++ pointers linked-list stack


【解决方案1】:

paxdiablo 在 cmets 中提到了答案:C++ 通过引用传递。示例:

#include <iostream>

struct node
{
    int data;
    struct node *link;
};

void push(node*& head)
{
    struct node *temp = new node;
    std::cout << "enter the value";
    std::cin >> temp->data;
    temp->link = head;
    head = temp;
}

int main()
{
    node *start = NULL;
    push(start);
    return 0;
}

【讨论】:

    【解决方案2】:

    替代实现:

    void push(struct node** head_reference, int new_data)
    {
        struct node* a_node = new node;
        a_node->data  = new_data;
        a_node->link = (*head_reference);    
        (*head_reference)    = a_node;
    }
    
    int main() {
        struct node* head = NULL;
        push(&head, 10);
        // rest of your code here
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-26
      • 2014-10-12
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 2014-07-27
      • 2023-03-03
      相关资源
      最近更新 更多