Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing matrix as a parameter in function

Tags:

c

matrix

I have been trying to write a function which gives the index of rows and columns whoses element is 0. I tried using a function

void make_zero(int matrix[][],int row,int col)
{
    int row, col;
    int i,j;  

    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            if(matrix[i][j]==0){
                printf("%d %d\n", i, j);
        }

    }
}

But at the time of compiling it gives an error"error: array type has incomplete element type". I also tried declaring the matrix globally and giving it a pointer. But it doesn't work for me. Help me out with this how can we pass matrix to a function in C.

like image 958
user2714823 Avatar asked Sep 06 '13 15:09

user2714823


People also ask

How do you call a matrix in a function?

matrix = variable(input1, input2); where 'matrix' is the output and 'variable' is the function name. 'input1' and 'input2' are also matrices of order 32x32.

Can we pass array as a parameter of function?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name.

When an array is passed as parameter to a function?

Explanation: When an array is passed as parameter to a function then the function can change values in the original array.


2 Answers

Try this

  void make_zero(int row, int col, int matrix[row][col])
  {
     int i,j;  
     for(i=0;i<row;i++)
        for(j=0;j<col;j++)
        {
            if(matrix[i][j]==0)
               printf("%d %d\n",i,j);
        }

  }
like image 107
haccks Avatar answered Oct 22 '22 11:10

haccks


Your problem is that multi-dimensional arrays in C need to have their lengths known except for the outermost value.

What you can do is pass the pointer to the memory holding the matrix and then cast it to the right type:

void make_zero(void* _matrix,int row,int col)
{
    int i,j;  
    int (*matrix)[col] = _matrix;
    for(i=0;i<row;i++)
        for(j=0;j<col;j++)
        {
             if(matrix[i][j]==0){
                   printf("%d %d\n",i,j);
        }

    }
}
like image 25
Sergey L. Avatar answered Oct 22 '22 11:10

Sergey L.