通过使用指针引用传递数组的混淆
confusion with passing arrays by reference using pointers
我几个小时前就问了一个问题,我已经与答案中指出的某些内容完全混淆了(使用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);
- 通过指针与数组引用扩展数组索引序列
- 将链表的内容放在数组引用中
- 是否允许使用初始值设定项列表将const数组引用实例化为构造函数参数
- C 在将数组引用分配给struct时麻烦
- Typedef数组引用
- 通过强制转换创建子数组引用
- 将数组引用 'T(&)[n]' 引用到 'std::array<T, n>' 的内容
- constexpr 数组引用参数
- 寻找有关函数定义和原型中数组引用的说明
- Initializer_list作为非模板上下文中数组引用参数的参数
- 如何使用一个动态创建的一维数组的二维数组引用仅与标准库?
- 如何返回具有大小的POD数组引用
- 在C++中返回数组引用的语法
- 是否可以声明转换函数返回数组引用而不使用typedef
- 自定义到数组引用的转换
- 类数组引用的NullReferenceException
- 数组指针与数组引用之间的差异
- 在c++中传递数组引用
- 使用特征矩阵作为特征数组引用的参数
- 如何从函数传递数组引用