我正在尝试创建一个单链表并交换子中的两个 int
元素
功能。
- 在函数
swap(int *a,int *b)
中,参数类型为int *
,可以成功运行。 - 在函数
build_sll(node *head)
中,单向链表不会创建成功。 - 一旦我将参数类型设置为
build_sll(node *&head)
,它就会成功创建单向链表。
混淆:
函数swap(int *a,int *b)
传递了a
b
的地址,我可以修改 a
b
的值。
函数 build_sll(node *head)
只传递了指针 head
的 value。我无法修改 head
的值。
为什么这里不传head
的address。它们之间的唯一区别是它们的数据类型。
在设置build_sll(node *head)
时,在GDB
我的代码之后,我发现所有的node
对象都已经创建成功.在 main
中,如果我访问分配的地址,它会记录 node
信息。在这种情况下如何删除内存。
查看我的代码以弄清楚我的问题。
#include<iostream>
#include<cstdlib>
#include<memory.h>
using namespace std;
typedef struct node{
int num;
struct node * next;
node(int num,struct node * next)
{
this->num = num;
this->next = next;
}
}node;
void build_sll(node *&head);
void del_memory(node *&head);
void travel_sll(node *head);
void swap(int *,int *);
int main()
{
int a =10 ,b = 5;
node *head = NULL;
build_sll(head);
travel_sll(head);
del_memory(head);
swap(&a,&b);
cout << a <<" "<< b <<"\n";
exit(0);
}
void build_sll(node *&head)
{
head = new node(0,NULL);
node * tail = head;
for(int index = 1 ; index < 8;index++)
{
node * temp = new node(index,NULL);
tail -> next = temp;
tail = temp;
}
}
void travel_sll(node *head)
{
if(head)
{
head = head -> next;
while(head)
{
cout << head->num <<"\n";
head = head -> next ;
}
}
}
void del_memory(node *&head)
{
delete [] head;
}
void swap(int *a,int *b)
{
int t;
t = *a;
*a = *b;
*b = t;
}
最佳答案
function
swap(int *a,int *b)
passed the address of a b, I could modify the value of a b . functionbuild_sll(node *head)
passed only the value of pointer head. I could not modify the value of head. why here does not pass the address of head. The only difference between them is their data type.
在函数 swap
中,您想要修改/访问 int
的值,因此传递 int *
或 int &
会工作。传递 int
类型的参数有利于读取参数的值,但如果您更改它,则只会更新本地拷贝,而不是您调用函数时使用的值。
在函数 build_sll
中,您想更改 node *
类型的参数。因此,您应该传递 node **
或 node *&
类型的参数,以确保您可以更改调用它的值。传递 node *
只会更改本地拷贝(在被调用函数中),被调用函数中的原始值将保持不变。
您的选择是:
- 首选
node * build_sll(node *);
- 确定
node * build_sll(node *&);
- 避免这种情况:
node * build_sll(node **);
等
关于c++ - 与指针引用和指针混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37941431/