【发布时间】:2009-09-04 16:26:03
【问题描述】:
我有一个函数,它根据表查找返回一个不同长度的数组。我在函数内部为它分配了所需的内存,但是我怎样才能从它的指针中填充数组呢? 编译器对我的两次尝试都抛出了相同的错误(注释行)。请帮忙!
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;
}
【问题讨论】:
标签: arrays initialization malloc dereference