Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a pointer to a multidimensional array in C?

I have a two dimensional array that works with a function:

bool matrix[rows][cols];
func(rows, cols, matrix);

void func(int rows, int cols, bool matrix[rows][cols]) {
    //...
}

However, as soon as I try to have matrix in the original function modified by:

bool matrix[rows][cols];
func(rows, cols, &matrix);

void func(int rows, int cols, bool *matrix[rows][cols]) {
    //...
}

I receive an incompatible pointer type error. I am clueless as to why.

like image 769
Synlar Avatar asked May 08 '16 07:05

Synlar


1 Answers

bool matrix[rows][cols] is an array of arrays of a type bool

bool* matrix[rows][cols] is an array of arrays of a type pointer to bool or simply bool*.

Thus if you defined your function to take an array of arrays of type bool*, you need to pass that type:

bool* m[row][col];
func( row , col , m );

If you want to have a pointer to bool matrix[rows][cols], then your approach is not correct.
A pointer to matrix has the type: bool (*pmatrix)[rows][cols]. So define your function with that type and pass the address of the matrix array:

func( rows , cols , &matrix );
like image 173
2501 Avatar answered Jan 07 '23 21:01

2501