简体   繁体   中英

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM