gpt4 book ai didi

c++ - 函数指针(列表)

转载 作者:行者123 更新时间:2023-11-30 03:55:23 25 4
gpt4 key购买 nike

我必须编写这个程序,但我不能对函数 main 做任何更改,该程序在 Node* head 被声明为全局变量时起作用(函数在参数中不包含“Node* head”)。该程序编译成功,但随后出现段错误(我知道为什么,Head 没有改变,它仍然是 0,但我不知道如何解决)。有什么想法吗?

#include <iostream>
#include <cstdlib>
using namespace std;
struct Node{
int val;
Node* next;
};
void addBeg(Node* head,int val)
{
Node* temp = (Node*)malloc(sizeof(Node));
temp->val=val;
temp->next=head;
head=temp;
}
int main()
{
Node* head=0;
addBeg(head,1);
cout << head->val << endl; //checking if head was changed correctly
return 0;
}

最佳答案

如果你想改变函数内部的指针,发送“指向指针的指针”,例如:

#include <iostream>
#include <cstdlib>
using namespace std;
struct Node{
int val;
Node* next;
};
void addBeg(Node** head,int val) // Node** instead of Node*
{
Node* temp = (Node*)malloc(sizeof(Node));
temp->val=val;
temp->next=*head;
*head=temp; // *head instead of head
}
int main()
{
Node* head=0;
addBeg(&head,1); // &head instead of head
cout << head->val << endl; //checking if head was changed correctly
return 0;
}

编辑:

或者只使用指针的引用参数:

void addBeg(Node* &head,int val)
{
Node* temp = (Node*)malloc(sizeof(Node));
temp->val=val;
temp->next=head;
head=temp;
}

关于c++ - 函数指针(列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29054586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com