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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With