Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing 2D array by reference to function

I am trying to add two matrices using 2D arrays in C. Here I am passing the array name as a parameter, which I think is pass by reference. However, I cannot add the arrays. Something is fishy in the add function, I cannot add the arrays.

I even tried to pass the parameter using address of Operator, however arrays are pointer themselves so it got error. I tried passing with the name of array. I am stuck

#include<stdio.h>
void input(int*,int*);
void add(int*,int*,int*);
void display(int*);

int main()
{
int a[3][3],b[3][3],sum[3][3];
 input(a,b);
 add(a,b,sum);
 display(sum);
 return 0;
 }

void input(int*a,int*b)
{
    for(int i = 0;i<3;i++)
    {
        for(int j =0;j<3;j++)
        {
            printf("Enter the element at a[%d][%d]",i+1,j+1);
            scanf("%d",((a+i)+j));
        }
    }
    for(int i = 0;i<3;i++)
    {
        for(int j =0;j<3;j++)
        {
            printf("Enter the element at b[%d][%d]",i+1,j+1);
            scanf("%d",((b+i)+j));
        }
    }
}
    void add(int* a,int*b,int*sum)
    {
        for(int i =0;i<3;i++)
        {
            for(int j=0;j<3;j++)
            {
                *(sum[i]+j) = *(a[i]+j) + *(b[i]+j);//error at this line
            }
        }
    }
 
 void display(int* sum)
  {
      printf("The sum is:\n");
      for(int i =0;i<3;i++)
      {
          for(int j =0;j<3;j++)
          {
            printf("%d ",(sum[i]+j));
          }
           printf("\n");
      }
  }

I got the following error

operand of '*' must be a pointer

However my operand is readily a pointer.

like image 996
IcanCode Avatar asked Feb 25 '26 12:02

IcanCode


1 Answers

The problem is that the methods:

void input(int*, int*);
void add(int*, int*, int*);
void display(int*);

expected a pointer, however you are passing to them 2D arrays (statically allocated), namely int a[3][3], b[3][3], sum[3][3];. Therefore, as already pointed out in the comments, those 2D arrays will be converted to 'int (*)[3]'. Consequently, you need to adapt the signature of your methods to:

void input(int [][3], int [][3]);
void add(int [][3], int [][3], int [][3]);
void display(int [][3]);

and

void input(int a[][3], int b[][3]){
      // the code
}

void add(int a [][3], int b [][3], int sum [][3]){
      // the code
}

void display(int sum [][3]){
      // the code
}    

Alternatively, if you want to keep the int* as parameter then what you can do is to allocate the matrix as a single array and adapt your code accordingly

like image 92
dreamcrash Avatar answered Feb 27 '26 01:02

dreamcrash