[英]how to pass a pointer to a function and create a matrix there with the pointer as the starting address?
应该打印相同的矩阵,但在 function 之外它不打印矩阵的任何值。 这里有什么问题?(我不希望 function 中的参数名称和传递的变量名称相同。)
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);
}
C 中的函数参数是按值传递的。 这意味着对tryn
中a
的更改不会反映在调用 function 中,因此main
中的arr
保持未初始化。
您需要将arr
的地址传递给您的 function:
tryn(&arr);
并相应地更改 function 中的参数类型:
void tryn(double **arr)
{
double *a=calloc(20,sizeof(double));
...
*arr = a;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.