Alex Rivera | Logout

Passing arrays and matrices to functions as pointers and pointers to pointers in C

Asked 2009-02-13T17:28:23.270
17

Given the following code:

void
foo( int* array ) 
{
    // ...
}

void
bar( int** matrix ) 
{
    // ...
}

int
main( void ) {
    int array[ 10 ];
    int matrix[ 10 ][ 10 ];

    foo( array );
    bar( matrix );

    return 0;
}

I don't understand why I get this warning:

warning: passing argument 1 of ‘bar’ from incompatible pointer type

Although 'foo' call seems to be ok.

Thanks :)

Edit
Report

1 Answer

15

Passing multi-dimensional arrays in C is a tricky subject. See this FAQ.

The question to ask is how you'll be using bar. If you always know it will be passed a 10x10 array then rewrite it as

bar(int matrix[10][10]);

If you want to cope with arrays of varying dimensions then you might have to pass in the lengths:

bar(int *matrix, int width, int height);
answered 2009-02-13T17:36:09.837

Your Answer