直接从指针/地址访问数组的元素

Accessing an array's elements directly from a pointer/address

本文关键字:访问 数组 元素 地址 指针      更新时间:2023-10-16

我想:

  • 将指向整数数组的指针传递给方法,
  • 使用方法中的值,
  • 调整方法中数组的大小,
  • 然后继续使用方法外部的数组。

我的方法声明有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
}