我有一个函数,它根据表查找返回一个不同长度的数组。我在函数内部为其分配所需的内存,但是如何从它的指针填充数组?编译器对我的两次尝试都抛出了相同的错误(注释行)。请帮忙!
int lookup(const char *name, float *factors) {
int length;
if(!strcmp(name, "foo")) {
length = 6;
factors = malloc(length * sizeof(float));
// *factors = {0, -0.9, -4.9, -8, -7.8, -23.9};
// factors = {0, -0.9, -4.9, -8, -7.8, -23.9};
}
else if(!strcmp(name, "bar"))
{
length = 4;
factors = malloc(length * sizeof(float));
// *factors = {0, -3, -6, -9};
}
// .......................
// more else if branches
// .......................
else // error: name not found in table
{
factors = NULL;
fprintf(stderr, "name not found in table!!\n");
return 0;
}
return length;
}