首页 > 解决方案 > 如何编写分配完整数据结构的函数

问题描述

正如我上面写的,我正在尝试编写一个分配数据结构的函数

这是我所做的,但是当我尝试使用索引调用 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
}

它抛出一个错误

下标值既不是数组也不是指针也不是向量

标签: cmalloc

解决方案


使用 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.

}

推荐阅读