通过使用指针引用传递数组的混淆

confusion with passing arrays by reference using pointers

本文关键字:数组 引用 指针      更新时间:2023-10-16

我几个小时前就问了一个问题,我已经与答案中指出的某些内容完全混淆了(使用C 中的指针:访问返回的数组时的分段故障中的数组)。有些人对我的新问题问题有所反应,所以我介绍了有关指针的书,这对我没有太大帮助。所以,我又去了。

在上一个问题中,我有一个函数 void builder(int aSize1, int aSize2, int aSize3, int*** frequencies),我认为它会动态分配传递给int*** frequencies参数的3D数组的内存并初始化它。但是,有人告诉我,只会将副本传递到该函数中,我将仅针对 copy 而不是原件分配和初始化。因此,他们建议我使用参考,将函数原型作为void builder(int aSize1, int aSize2, int aSize3, int***& frequencies)

渲染。

但是,我回想起昨天,当我第一次通过使用指针引用的通行概念偶然发现了这一通行证时,人们也能够操纵指针的数据。机智,

void change_what_this_points_to( int* a )
{
    *a = 42;
}

此功能确实会更改馈入函数的指针的值。

那么,我的问题是,为什么前者在后者通过 real Deal 时将其传递?除了有更多星号之外,我没有看到两个功能之间的区别。

任何帮助将不胜感激。谢谢!

,而另一个答案表明,我只是以为我会添加两分钱,以防万一它有所帮助。将指针视为内存中的地址。您将该地址传递到一个函数中,并且该函数在其中写入一些内容。然后,在调用该功能后,您可以在内存中的同一位置查看并查看那里的值。

因此,假设您有以下代码:

void SetValue(int *a){ *a = 10;}
void DoWork()
{
    int a; 
    SetValue(&a); 
}

setValue函数作为参数作为一个指向int的指针,或者正如我们将想到的那样,在存储int的内存中的地址。然后,该函数将数字10写入地址中传递的数字。

dowork方法然后为int创建内存,并将该内存的地址传递给函数。因此,到Dowork返回存储的内存时,存储的" A"具有值10。听起来您已经从您的问题中获得了此内容,但想从这里开始,以防万一。

现在,让我们假装您想要一个函数来为您分配内存。您真正要求该功能要做的是分配内存并告诉我该内存在哪里。因此,您可以使用指针返回值来完成此操作,即

int* AllocateMemoryForMe()
{
    return new int(); //Creates memory for an int, let's pretend it's at location 0x100
}
void DoWork()
{
    int* a = NULL; // a has a value of 0x00
    a = AllocateMemoryForMe(); //a will now have the value of 0x100
    *a = 10; //We now write 10 to memory location 0x100
}

,也可以使用指针进行此操作。如果执行此操作,您实际要做的就是将内存中的位置传递到函数中,将分配的内存的地址写入指向指针的指针。因此,当功能返回时,您可以查看此地址,并查看新创建的内存的地址。因此:

void AllocateMemoryForMe(int** x)
{
    *x = new int(); //allocates memory for an int, let's pretend it's at memory location 0x200
}
void DoWork()
{
    int** a = new int*(); //Creates memory for an int pointer. Let's pretend it allocates memory at location 0x100. 
    AllocateMemoryForMe(a); //pass memory location 0x100 to the function.
    //Right now the address of a is still 0x100 but the data at the memory location is 0x200. This is the address of the int we want to write to.
    **a = 10; //This will now write 10 to the memory location allocated by the AllocateMemoryForMe() function. 
}

此功能

void change_what_this_points_to( int* a )
{
    *a = 42;
}

不会更改指针本身。它更改了指针指向的整数对象。

如果要更改指针本身,则应以以下方式编写功能

void change_what_this_points_to( int * &a )
{
    a = new int( 42 );
}

或以下方式

void change_what_this_points_to( int **a )
{
    *a = new int( 42 );
}

因此,返回您的功能,您应该像

那样声明它
void builder(int aSize1, int aSize2, int aSize3, int*** &frequencies);

或喜欢

void builder(int aSize1, int aSize2, int aSize3, int**** frequencies);