C++: make one matrix point to another
all. I have an interesting question, posed to me by my C++ professor. It is also used in some programming job interviews, appare开发者_C百科ntly.
Here's the situation. I have a two-dimensional array (matrix) of int's:
int array1[][2] = {{11, 12}, {21, 22}};
I would like to create a second two-dimensional array, array2, that points to this first array. That is, they would occupy the same space in memory.
The obvious solution is to use pointers. So, I declared array2 like so:
int (*array2)[2][2];
array2 = &array1;
This seems to work. Now, here's the catch. I am trying to subtract 11 from array1, but do it by referencing array2. Here is the code for what I'm trying to accomplish:
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;
}
}
I have tried the following in the body of the internal for-loop, all without success:
// 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;
Any ideas? I suspect there's something simple that I'm just not getting here.
Thanks!
array2
points to array1
, so you can get to array1
with *array2
. Try (*array2)[i][j]
.
Since this is C++, you can create an alias array using a reference, that's exactly what they do.
int array1[][2] = {{11, 12}, {21, 22}};
int (&array2)[2][2] = array1;
for(int i=0; i<2; ++i)
for(int j=0; j<2; ++j)
array2[i][j] -= 11;
Although the problem is more likely a C problem with the expectation that array2 would be a pointer to the first row of array1
int array1[][2] = {{11, 12}, {21, 22}};
int (*array2)[2] = array1;
for(int i=0; i<2; ++i)
for(int j=0; j<2; ++j)
array2[i][j] -= 11;
精彩评论