有没有办法在 C++ 中创建一个行为类似于子数组的指针?就像这个答案一样, 但有 2 个维度。更具体地说,我想拥有
int arr[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
int subarr ** = arr[1][1];
这样subarr[0][0] == 5
No this is not possible. In your example, the array would not reside in continuous memory so can not be accessed properly with the array subscript.
I am assuming that you would expect the subarr
to contain {{5,6},{8,9}}
.
arr
would appear in memory as (the | is for visualisation only):
| 1 2 3 | 4 5 6 | 7 8 9 |
subarr
woud be trying to pick out certain elements which cannot be achieved with the multiply by dimension and add offset approach of the array subscript operator:
1 2 3 4 5 6 7 8 9
^ ^ ^ ^
Not for an array of ints (a 2D array of ints is still an array of ints). If you had an array of pointers to int arrays, then yes. Then the question makes sense and the answer is obvious.