典型方法其指針返回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