[英]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];
my_array
is a pointer that points to what? my_array
是一个指向什么的指针? 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::vector
或std::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.