Skip matrix as argument

I want to pass two matrices as an argument. These matrices have different sizes, and I don’t understand how I should do this work:

#include <stdio.h>
#include <stdlib.h>


void f(int m[3][], int n);

int main()
{
  int A[3][3]={{1,2,3},{4,5, 6},{7,8,9}};
  int B[3][2]={{1,2},{3, 4}, {5, 6}};

  f(A, 3);
  f(B, 2);

  return 0;
}

 void f(int m[3][], int n)
 {
    int i,j;
    for(i=0;i<3;i++)
    {
      for(j=0;j<n;j++)
       printf("%5d", m[i][j]);
    }
    return;
 }

How can i do this?

+5
source share
1 answer

The only safe way I know for this is to include the dimensions of the matrix in the parameters or make some kind of struct structure

Option A) Dimensions as parameters

void f(int **m, int w, int h )
{
    int i,j;
    for(i=0;i<w;i++)
    {
      for(j=0;j<h;j++)
         printf("%5d", m[i][j]);
    }
    return;
}

Option B) Use a struct

typedef struct Matrix
{
    int w, h;
    int** m;
} Matrix;

void f ( Matrix *m )
{
    for ( int i = 0; i < m->w; ++i )
    {
        for ( int j = 0; j < m->h; ++j )
        {
            printf(%5d", m->m[i][j]);
        }
    }
}
+6
source

All Articles