0

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?

kbyrd
  • 3,321
  • 27
  • 41

1 Answers1

3

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.

joerick
  • 16,078
  • 4
  • 53
  • 57
  • Now that sounds better, +1. Please delete your incorrect answer in the meantime - you'll get back the -2 reputation :) –  Aug 26 '12 at 16:05
  • Duh! I knew this at some point, but stopped thinking because I assumed objective-c was somehow different w.r.t arrays or typedefs. I keep forgetting I can just do regular C tricks with it. I should have remembered that I need typedefs for anything more complicated than a 1d array! – kbyrd Aug 26 '12 at 19:48