正如我上面写的,我正在尝试编写一个分配数据结构的函数
这是我所做的,但是当我尝试使用索引调用 T 时它会抛出错误
typedef struct {
float *tab;
int nbCases;
}dyntab;
void initDyn(dyntab *dtab, int size){
dtab=malloc(size*sizeof(dyntab));
}
int main(){
dyntab T;
initDyn(&T, 10); // for example allocating a table with 10 cases
}
它抛出一个错误
下标值既不是数组也不是指针也不是 vector
使用 VLA。
typedef struct {
size_t nbCases;
float tab[];
}dyntab;
dyntab *allocdyntab(dyntab *d, size_t size)
{
dyntab *temp = realloc(d, size * sizeof(d -> tab[0]) + sizeof(*d));
if(temp)
{
temp -> nbCases = size;
}
return temp;
}
当你传入 NULL 时,它会分配新的内存,否则它会重新分配内存
int main(){
dyntab *T = NULL;
T = allocdyntab(T, 10); // for example allocating a table with 10 cases
/*or*/
//dyntab *T = allocdyntab(NULL, 10);
/* another code */
T = allocdyntab(T, 50); // change the size of already alllocated one without loosing the content
//you should add the temp variable and check the allocation result.
}