Confusion in the c code

135 Views Asked by At

I have a doubt in this code that why does the values that i give in the readMat() actually get stored in a and b??

I mean isn't this call by value and not by reference?

Oh if there is any other thing i am doing wrong please tell me. I will be thankful.

Thanx in advance.

#include<stdio.h>

struct spMat
{
    int rowNo;
    int colNo;
    int value;
}a[20],b[20],c[20],d[20],e[20];

void readMat(struct spMat x[20])
{
    printf("Enter the number of rows in the sparse matrix\n");
    scanf("%d",&x[0].rowNo);
    printf("\nEnter the number of columns in the sparse matrix\n");
    scanf("%d",&x[0].colNo);
    printf("\nEnter the number of non-zero elements in the sparse matrix\n");
    scanf("%d",&x[0].value);

    int r=x[0].rowNo;
    int c=x[0].colNo;
    int nz=x[0].value;
    int i=1;

    while(i<=nz)
    {
        printf("\nEnter the row number of element number %d\n",i);
        scanf("%d",&x[i].rowNo);
        printf("\nEnter the column number of element number %d\n",i);
        scanf("%d",&x[i].colNo);
        printf("\nEnter the value of the element number %d\n",i);
        scanf("%d",&x[i].value);
        i++;
    }
}

void printMat(struct spMat x[20])
{
    int k=1,i,j;

    for(i=0;i<x[0].rowNo;i++)
    {
        for(j=0;j<x[0].colNo;j++)
        {
            if((k<=x[0].value)&&(x[k].rowNo==i)&&(x[k].colNo==j))
            {
                printf("%d\t",x[k].value);
                k++;
            }

            else
                printf("%d\t",0);
        }

        printf("\n");
    }
}

void fastTranspose(struct spMat x[20])
{

}

void addMat(struct spMat x[20], struct spMat y[20])
{

}

void multMat(struct spMat x[20], struct spMat y[20])
{

}

void main()
{
    readMat(a);
    readMat(b);
    printMat(a);
    printMat(b);
}
3

There are 3 best solutions below

0
On

"When arrays are passed as function arguments, they "decayed" into pointers"

small ex:

void f(int b[])
{
  b++;
  *b = 5;
}
int main()
{
  int arr[] = {1,2,3,4};
  f(arr);
  printf("%d",arr[1]);
  return 0;   
}            
9
On

Yes, it's call-by-reference. In C, arrays are passed to functions by passing the address of the first element, just as if you'd declared your function as:

void readMat(struct spMat *x);
1
On

Technically, C only supports call-by-value. When arrays are passed as function arguments, they "decayed" into pointers. And when you pass pointers, you are still passing it by value, i.e, the value of the pointer, but you can modify what the pointer points.

You can think it as if call-by-reference when passing pointers, but need to understand what really happened.