0

I have 2 static matrices. a[][N] and b[][M]. Both N and M are pre defined and are not equal to each other. Now how am I supposed to write functions that can recieve them both and work properly?

void PrintStaticMatrix(int matrix[][??], int rows, int cols);

What am I going to need to put insted of ??. The naive way is to seperate the function into two functions; they will be exactly the same, but one is for N and the other one is for M. Howeve, it does not seem to make any sense. Is not there a better way? I would have much perferred to use only dynamic arrays, but we are forced to in an advanced C course.

Algo
  • 178
  • 7

1 Answers1

4

If your compiler supports variable length arrays you can declare the function like

void PrintStaticMatrix( int rows, int cols, int matrix[rows][cols] );

or

void PrintStaticMatrix( int rows, int cols, int matrix[][cols] );

or

void PrintStaticMatrix( int rows, int cols, int ( *matrix )[cols] );

Another approach is to use dynamically allocated arrays as for example

int **matrix = malloc( rows * sizeof( int * ) );
for ( int i = 0; i < rows; i++ )
{
    matrix[i] = malloc( cols * sizeof( int ) );
}

And declare the function like

void PrintStaticMatrix( int **matrix, int rows, int cols );

One more approach is reinterpret a two-dimensional array as a one-dimensional array. In this case the function will look like

void PrintStaticMatrix( int *matrix, int rows, int cols );

And a function call can look like

PrintStaticMatrix( ( int * )matrix, rows, cols );

Within the function you will deal with a one-dimensional array. Using an appropriate expression as an index you will be able to simulate a two-dimensional array for example in for loops.

Otherwise you will need two separate functions like

void PrintStaticMatrix1( int matrix[][M], int rows );

and

void PrintStaticMatrix2( int matrix[][N], int rows );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335