bgroenks bgroenks - 3 months ago 16
C Question

C Access Multi-Dimensional Array

I'm getting a subscripting compiler error when trying this:

int **arrays;
// allocate and initialize it....
int pos1 = 0;
int pos2 = 1;
int value = (*arrays[pos1])[pos2];


If the part in parentheses dereferences to a
int*
pointer, why would the array access not be legal?

Answer

The part in parentheses is an int. Firstly, arrays[pos1] yields a pointer (int*), that you then have dereferenced (via the pre-fixed * operator). Thus, (*arrays[pos1]) is a simple int, and not a pointer.

If your goal is simply to access a position with in a multi-dimensional array, forget the * and just use:

arrays[pos1][pos2]