d kumar
d kumar

Reputation: 11

how to pass a pointer to a function and create a matrix there with the pointer as the starting address?

Same matrix should be printed but here outside the function its not printing any value of the matrix. What is the issue here?(I dont want the argument name in function and name of variable passed to be same.)

0.000000 0.000000 0.000000 0.000000 0.000000
1.000000 1.000000 1.000000 1.000000 1.000000
2.000000 2.000000 2.000000 2.000000 2.000000
3.000000 3.000000 3.000000 3.000000 3.000000

0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 0.000000

#include<stdio.h>
#include<stdlib.h>

void tryn(double *a)
{
    int i,j;
    a=(double *)calloc(20,sizeof(double));
    for(i=0;i<4;i++)
    {
        for(j=0;j<5;j++)
        {
            *(a+i*5+j)=i;
        }
    }

    for(i=0;i<4;i++)
    {
        for(j=0;j<5;j++)
        {
            printf("%lf ",*(a+i*5+j));
        }
        printf("\n");
    }


}
int main()
{
    int i,j;
    double *arr;
    tryn(arr);
    for(i=0;i<4;i++)
    {
        for(j=0;j<5;j++)
        {
            printf("%lf ",(arr+i*5+j));
        }
        printf("\n");
    }
    free(arr);
}

the output its giving

Upvotes: 1

Views: 44

Answers (1)

dbush
dbush

Reputation: 224522

Parameters to functions in C are pass by value. That means that changes to a in tryn are not reflected in the calling function, so arr in main remains uninitialized.

You need to pass the address of arr to your function:

tryn(&arr);

And change the parameter type in the function accordingly:

void tryn(double **arr)
{
    double *a=calloc(20,sizeof(double));
    ...
    *arr = a;
}

Upvotes: 0

Related Questions