c++ - 与指针引用和指针混淆

标签 c++ pointers reference

我正在尝试创建一个单链表并交换子中的两个 int 元素 功能。

  1. 在函数swap(int *a,int *b)中,参数类型为int *,可以成功运行。
  2. 在函数build_sll(node *head)中,单向链表不会创建成功。
  3. 一旦我将参数类型设置为build_sll(node *&head),它就会成功创建单向链表。

混淆:

函数swap(int *a,int *b)传递了ab地址,我可以修改 a b 的值。 函数 build_sll(node *head) 只传递了指针 headvalue。我无法修改 head 的值。 为什么这里不传headaddress。它们之间的唯一区别是它们的数据类型。

在设置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 . function build_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/

相关文章:

循环精确模型指针和数组

c++ - 临时对象混淆

c++ - 自由函数与成员函数

c++ - c歧义中的字母数字到数字

c - 如何访问数组的移动部分

c++ - 固定不安全指针

java - 是否有具有通用引用接口(interface)的标准库?

c# - 获取 Type 中使用的程序集的路径

c++ - 正确返回 vector 引用

c++ - 可以将 boost 累加器用作类成员