简体   繁体   English

当指向动态分配的内存时,指针的指针将分配什么值?

[英]What value does a pointer to pointer get assigned when points to a dynamically allocated memory?

Consider the following case: 考虑以下情况:

int **my_array = new int*[10];
  1. What do we assign to my_array here? 我们在这里分配给my_array什么?
  2. my_array is a pointer that points to what? my_array是一个指向什么的指针?
  3. Is there any way to iterate through my_array (the pointer) and set up a two-dimensional array of integers (and not int*)? 有没有办法遍历my_array(指针)并设置一个二维整数数组(而不是int *)?

We assign to my_array the address of an array. 我们为my_array分配一个数组的地址。 The array contains pointers which can point to other arrays, but don't yet. 该数组包含可以指向其他数组的指针,但还不能指向其他数组。

Yes, we can do this: 是的,我们可以这样做:

int **my_array = new int*[10];

for(int i=0; i<10; ++i)
  my_array[i] = new int[13];

my_array[2][11] = 500;

What do we assign to my_array here? 我们在这里分配给my_array什么?

You can assign an int* to the elements of my_array . 您可以将int*分配给my_array的元素。 Eg 例如

my_array[0] = new int[20];

or 要么

int i;
my_array[0] = &i;

my_array is a pointer that points to what? my_array是一个指向什么的指针?

It points to an an array of 10 int* objects. 它指向一个由10个int*对象组成的数组。

Is there any way to iterate through my_array (the pointer) and set up a two-dimensional array of integers (and not int*)? 有没有办法遍历my_array (指针)并设置一个二维整数数组(而不是int *)?

Not sure what you are expecting to see here. 不知道您期望在这里看到什么。 An element of my_array can only be an int* . my_array的元素只能是int*

If you want my_array to be a pointer to a 2D array, you may use: 如果希望my_array成为2D数组的指针,则可以使用:

int (*my_array)[20] = new int[10][20];

Now you can use my_array[0][0] through my_array[9][19] . 现在您可以通过my_array[9][19]使用my_array[0][0] my_array[9][19]

PS If this is your attempt to understand pointers and arrays, it's all good. PS:如果这是您尝试了解指针和数组,那么一切都很好。 If you are trying to deploy this code in a working program, don't use raw arrays any more. 如果您尝试在工作程序中部署此代码,请不要再使用原始数组。 Use std::vector or std::array . 使用std::vectorstd::array

For a 1D array, use: 对于一维数组,请使用:

// A 1D array with 10 elements.
std::vector<int> arr1(10);

For a 2D array, use: 对于2D阵列,请使用:

// A 2D array with 10x20 elements.
std::vector<std::vector<int>> arr2(10, std::vector<int>(20)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM