C Question

Ways to pass 2D Array to function in C

I started learning C language a week ago.
Just for the test I decided to write a tictactoe game.

I have a field.

int field[3][3];

And a function printField

void printField(int field[3][3]){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
printf("%i", field[i][j]);

It's working in main like this:

int main(){

BUT if I change

void printField(int field){...}


void printField(int field[][]){...}

It gives me a bunch of errors:

subscripted value is neither array nor pointer nor vector
passing argument 1 of ‘printField’ makes integer from pointer without a cast
note: expected ‘int’ but argument is of type ‘int (*)[3]’

Why can't I pass the array like this?
Are there any more ways to pass it?

Answer Source

The function is independent of any call to the function. So the function cannot guess from the rest of the program what the array size is. In the function body you have to have constants or variables to represent all dimensions.

You can use variables for this instead of fixed size:

void printField(int r, int c, int field[r][c])
    for(int i = 0; i < r; i++)
        for(int j = 0; j < c; j++)
            printf("%i", field[i][j]);


And to call the function:

printField(3, 3, field);

You can compute the dimensions from the array's name. Using a macro confines the ugly syntax:

#define printField(a) printField( sizeof(a)/sizeof((a)[0]), sizeof((a)[0]) / sizeof((a)[0][0]), (a) )

int f1[3][3] = { 0 };

int f2[4][5] = { 0 };
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download