直接从指针/地址访问数组的元素
Accessing an array's elements directly from a pointer/address
我想:
- 将指向整数数组的指针传递给方法,
- 使用方法中的值,
- 调整方法中数组的大小,
- 然后继续使用方法外部的数组。
我的方法声明有func(int**arr_address),我称该方法为func(&arr)。一种方法是在我的方法中分配局部变量,但这似乎很笨拙。我尝试使用的方法是直接访问数组元素,例如 *arr_address[1],但这似乎将 [1] 偏移量应用于指针的内存地址,而不是数组数据在内存中开始的位置的地址。
这是一个带有输出的简单程序,用于说明两种不同的方法:
#include <iostream>
#include <stdlib.h>
void func(int** arr1_address, int** arr2_address)
{
int* arr1_local = *arr1_address;
arr1_local[1]=2; // Works
*arr2_address[1]=22; // (*) Writes to position 0 of wrong array!
// These realloc() calls were incorrect in the original question
//arr1_address = (int**)realloc(*arr1_address, 3*sizeof(int));
//arr2_address = (int**)realloc(*arr2_address, 3*sizeof(int));
*arr1_address = realloc(*arr1_address, 3*sizeof(int));
*arr2_address = realloc(*arr2_address, 3*sizeof(int));
//arr1_local[2] = 3;
//*arr2_address[2] = 33;
}
int main()
{
int* arr1;
int* arr2;
arr1 = (int*)calloc( 2, sizeof(int) );
arr2 = (int*)calloc( 2, sizeof(int) );
arr1[0] = 1;
arr2[0] = 11;
std::cout << "arr1, before func(): " << &arr1 << std::endl;
std::cout << "arr2, before func(): " << &arr2 << std::endl;
func(&arr1, &arr2);
std::cout << "arr1, after func(): " << &arr1 << std::endl;
std::cout << "arr2, after func(): " << &arr2 << std::endl;
std::cout << "" << std::endl;
std::cout << "arr1: " << std::endl;
std::cout << arr1[0] << std::endl;
std::cout << arr1[1] << std::endl;
std::cout << arr1[2] << std::endl;
std::cout << "" << std::endl;
std::cout << "arr2:" << std::endl;
std::cout << arr2[0] << std::endl;
std::cout << arr2[1] << std::endl;
std::cout << arr2[2] << std::endl;
return 0;
}
输出如下所示:
arr1, before func(): 0xffffcc08 // Note offset after arr2 location in memory
arr2, before func(): 0xffffcc00
arr1, after func(): 0xffffcc08 // realloc did not move the arrays
arr2, after func(): 0xffffcc00
arr1:
22 // Note line marked (*) wrote here instead of arr2[1]
2
66594
arr2:
11
0
66554
我很确定我理解为什么标有 (*) 的行以这种方式工作。我想知道是否有类似的方法直接从其地址寻址 arr2 的 [1] 元素。
(抱歉,如果之前有人问过这个问题,我已经阅读了不少答案,并在询问之前尽力调查。
编辑:更好的标题,修复realloc()行中的错误
我想知道是否有类似的方法直接从其地址寻址
arr2
的[1]
元素。
将[]
应用于arr2_address
时看到该行为的原因是[]
的优先级高于*
。您可以通过应用括号来强制使用所需的优先级:
(*arr2_address)[1] = 22;
您的问题在于不了解指针指向指针构造中的哪些指针指向哪些数据。如果您有多个级别的指针,请停止并绘制图片。
通常,您几乎永远不应该使用指向指针的指针。这种情况也不例外。您希望通过引用传递。为此使用实际引用。
void func(int*& arr1, int*& arr2)
{
arr1[0] = 42; // simple, easy
arr1 = realloc (arr1, 42*sizeof(int)); // simple, easy
free (arr2); // simple, easy
arr2 = malloc (42*sizeof(int)); // simple, easy
}
相关文章:
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 使用指针访问数组中的对象数据成员
- VTK 图像数据,访问数组中的 1 个图像
- 调用函数后无法访问数组
- 如何从地图访问数组的元素?
- 访问数组中的不同元素
- 使用指针访问数组元素时出现意外结果
- 使用指针访问数组的值
- C++基于1而不是0的访问数组,方法是在编译时移位
- 如何在主函数之外访问数组?
- 如何在 llvm 的 cpp api 中使用 CreateInBoundsGEP 来访问数组的元素?
- 访问数组中所有结构的成员
- C 是否每次访问数组时都复制元素?
- C++ 为什么访问数组中的元素会返回指针?
- 如何通过指针访问数组的元素
- 指针数组交换无需直接访问数组
- 直接从指针/地址访问数组的元素
- 我有一个 Qt 对象的 2d 数组,我已经用值播种了这些对象。如何访问数组中特定对象的值并更改它们?
- 如何使用 C+ 中的指针访问数组中的特定索引
- 通过两个下标访问数组成员