我有一个返回float*的函数,它实际上在返回函数中作为数组填充
float* some_fnc()
{
float *x=malloc(sizeof(float)*4);
x[0]=......
}
...
// in main
float y[4];
y=some_fnc();
Run Code Online (Sandbox Code Playgroud)
但是我收到"不兼容的类型"错误,这是正常的吗?有没有办法克服这个w/o声明y为浮动*?
C不支持/允许分配数组(即使它确实支持数组的初始化,这看起来像赋值).您有多种选择.一种是将数组的地址传递给函数,并让它填充现有的数组而不是为它分配空间:
void some_func(float *array, int size) {
for (i=0; i<size;i++)
array[i] = ...
// ...
}
Run Code Online (Sandbox Code Playgroud)
另一种可能性是在main中只有一个指针来保存函数返回的指针:
float *y = some_fnc();
// use y. Note that array style notation (y[0], y[1], etc.) is still allowed.
// when you're done with y.
free(y);
Run Code Online (Sandbox Code Playgroud)