c - 如何编写分配完整数据结构的函数

标签 c malloc

<分区>

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

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

}

关于c - 如何编写分配完整数据结构的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56097565/

相关文章:

c - 3D数组的动态内存分配

C:使用 qsort 对二维数组进行逐行排序

c - 如何在c中为微 Controller 定义新端口

c - 查找最小值和最大值

c - 下标值不是数组也不是指针

c - C 中多维数组的内存分配问题

c++ - 使用 Eigen 库的编译错误

c - 为什么 init_color() 在 Terminal.app 中无效?

java - 在 JNA 中传递带有内存字段的结构

c - 中止(核心转储)