This question already has answers here:
Closed 6 months ago.
Memory allocated with malloc does not persist outside function scope?
(6个答案)
正如我在上面写的,我试图编写一个分配数据结构的函数
这是我所做的,但是当我试图用索引调用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
}

它抛出了一个错误
下标值既不是数组也不是指针也不是向量

最佳答案

到目前为止,您正在为有泄漏的局部变量分配dyntab内存。

void initDyn(dyntab *dtab, int size){
    dtab=malloc(size*sizeof(dyntab));
}

也许你想要
void initDyn(dyntab *dtab, int size){
    dtab->tab=malloc(size*sizeof(float));
    dtab->nbCases = size;
}

07-24 09:51
查看更多