I'd like to clarify a concept that I haven't been able to fully understand.
Why in C is the type int **m
compatible with int *m[N]
, but not with int m[N][N]
? An 2D-array can be seen as a pointer to an array of integers, so int (*m)[N]
. However, it could also be seen as an array of pointers to integers, so int *m[N]
. What I don't understand is why int **m
cannot be seen as int m[][]
but as int *M[]
, while int m[][]
can be seen as int (*m)[]
but not as int **m.
I apologize if this explanation seems a bit confusing.
int m[X][Y]
couldn't possibly decay into an int **
since m
contains no pointers to which the int **
could point.
Array T m[X]
decays into a pointer to its first element (&m[0]
) when used as a pointer. Since the element has type T
, this pointer will obviously have the type T *
.
Example m |
T , the type of m[0] |
T * , the type of &m[0] |
---|---|---|
int m[X] |
int |
int * |
int m[X][Y] |
int[Y] |
int (*)[Y] |
Here's how you could pass a 2d array (so to speak) to a function:
void f( size_t x, size_t y, int (*m)[y] ) {
// ...
}
int m[X][Y];
f( X, Y, m );