Subscripting a pointers interchangeably with a 2D array in Objective-C?
-
28-06-2021 - |
Question
I have a statically declared array like this Cell SMatrix_A[36][10]
. When I use SMatrix_A directly in my code (Cell foo = SMatrix_A[12][8]
), everything works fine. However, what I really want is to declare several of these matrices (SMatrix_A, SMatrix_B, etc) and then have a pointer variable switch between them at runtime.
I'm imagining code like this (asusming SMatric_A, B, C are already declared and this is all in the same file scope):
Cell *curMatrix = SMatrix_B;
Cell foo,bar;
...
foo = curMatrix[13][2];
The compiler gives me an: Incompatable pointer types assigning 'Cell*' from 'Cell[36][10]'
on the initial assignment to curMatrix. I thought that referring to an array variable without subscripts was going to give me a pointer type with the value being the first location of the array.
Am I just missing a cast or something?
Solution
My previous answer is totally wrong, so I'm giving it another shot!
#import <Foundation/Foundation.h>
typedef int matrix_t[3][3];
matrix_t matrix = { { 1, 2, 3}, { 4, 5, 6}, { 7, 8, 9} };
int main(int argc, char *argv[])
{
matrix_t *matrixPtr = &matrix;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
NSLog(@"%i", (*matrixPtr)[i][j]);
}
}
return 0;
}
You need to typedef your 2D array type (this is likely a good idea so that your SMatrix_A, SMatrix_B all have the same size). Then you can create pointers to it as normal. Note that you must dereference the pointer before you index it.