Ways to pass 2D Array to function in C -


i started learning c language week ago. test decided write tictactoe game.

i have field.

int field[3][3]; 

and function printfield

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

it's working in main this:

int main(){ printfield(field);} 

but if change

 void printfield(int field){...} 

or

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

it gives me bunch of errors:

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

why can't pass array this? there more ways pass it?

the function independent of call function. function cannot guess rest of program array size is. in function body have have constants or variables represent dimensions.

you can use variables instead of fixed size:

void printfield(int r, int c, int field[r][c]) {     for(int = 0; < r; i++)         for(int j = 0; j < c; j++)             printf("%i", field[i][j]);      printf("\n"); } 

and call function:

printfield(3, 3, field); 

you can compute dimensions array's name. using macro confines ugly syntax:

#define printfield(a) printfield( sizeof(a)/sizeof((a)[0]), sizeof((a)[0]) / sizeof((a)[0][0]), (a) )  int f1[3][3] = { 0 }; printfield(f1);  int f2[4][5] = { 0 }; printfield(f2); 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -