Kar*_*ing 2 c++ pointers multidimensional-array
所有.我的C++教授向我提出了一个有趣的问题.它显然也用于一些编程工作面试.
这是情况.我有一个int的二维数组(矩阵):
int array1[][2] = {{11, 12}, {21, 22}};
Run Code Online (Sandbox Code Playgroud)
我想创建第二个二维数组array2,它指向第一个数组.也就是说,它们会在内存中占据相同的空间.
显而易见的解决方案是使用指针.所以,我像这样声明了array2:
int (*array2)[2][2];
array2 = &array1;
Run Code Online (Sandbox Code Playgroud)
这似乎有效.现在,这是抓住了.我试图从array1中减去11,但是通过引用array2来实现.这是我想要完成的代码:
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
// Trying to do the equivalent of this:
array1[i][j] -= 11;
}
}
Run Code Online (Sandbox Code Playgroud)
我在内部for循环的主体中尝试了以下内容,但都没有成功:
// Second row not affected
*(array2[i][j]) -= 11;
// Second row not affected
*(*(array2[i]) + j) -= 11;
// incompatible types in assignment of `int' to `int[2]'
*( *(array2 + i) + j) -= 11;
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?我怀疑有一些简单的东西,我只是没有来到这里.
谢谢!