2

Is there a way to create a pointer that behaves like a sub array in C++? Like the answer of this but with 2 dimensions. More specifically I want to have

int arr[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
int subarr ** = arr[1][1];

such that subarr[0][0] == 5

Community
  • 1
  • 1
ratatosk
  • 373
  • 5
  • 19

2 Answers2

1

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
        ^ ^   ^ ^      
DrYap
  • 6,525
  • 2
  • 31
  • 54
0

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.

xen-0
  • 709
  • 4
  • 12