Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass matrix as argument

Tags:

c

matrix

c89

I want to pass two matrices as argument. These matrices have different size and i don't understand how i have to 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?

like image 918
Nick Avatar asked May 16 '12 19:05

Nick


People also ask

When array is passed as an argument it indicates the?

1) In C, if we pass an array as an argument to a function, what actually get passed? The correct option is (b). Explanation: In C language when we pass an array as a function argument, then the Base address of the array will be passed.

Can be passed as an argument to a function?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.

When passing an array to a function How must the array argument be written how is the corresponding formal argument written?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.


1 Answers

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

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]);
        }
    }
}
like image 96
Dan F Avatar answered Oct 12 '22 01:10

Dan F