典型方法其指针返回multpile值是使用阵列和传递给功能:
int f(double *h) {
h[0] = 1.1;
h[1] = 2.2;
}
int main()
{
// create pointer
double *h;
// initialize it with memory block
h = malloc(2*sizeof(double));
// call the function
f(h);
// show output
printf_s("%8.5f \n", h[0]);
printf_s("%8.5f \n", h[1]);
// release memory block
free(h);
return 0;
}
此外同一阵列可以在没有存储器分配被创建。它更简单,但是只有在执行不会离开声明的函数范围时才存在数组。
int main()
{
// create array
double h[2];
// call the function
f(h);
// show output
printf_s("%8.5f \n", h[0]);
printf_s("%8.5f \n", h[1]);
return 0;
}
如果你只能在函数知道元素的数叫你可以在功能分配数组和指针数组返回,在主叫方释放阵列。
double* f() {
// create pointer
double *h;
// some size calculations
int size = 1+1;
// initialize it with memory block
h = malloc(size*sizeof(double));
// fill the array
h[0] = 1.1;
h[1] = 2.2;
// return array by pointer
return h;
}
int main()
{
// create pointer
double *h;
// call the function
h = f();
// show output
printf_s("%8.5f \n", h[0]);
printf_s("%8.5f \n", h[1]);
// release memory block
free(h);
return 0;
}
创建一个地方来存储它们并返回一个指针。 – jthill
你想返回h和n的最终值,还是返回所有这些值的数组/列表? – MateoConLechuga
在C中搜索数组,并将数组传递给函数。 – Evert