c - 如何编写分配完整数据结构的函数
问题描述
正如我上面写的,我正在尝试编写一个分配数据结构的函数
这是我所做的,但是当我尝试使用索引调用 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
}
它抛出一个错误
下标值既不是数组也不是指针也不是向量
解决方案
使用 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# - 在 Outlook 中识别电子邮件
- amazon-web-services - AWS SAM(无服务器应用程序模型)和无服务器框架有什么区别?
- javascript - node.js 模块没有自注册
- java - 以编程方式更改导航视图标题图像不起作用
- android - TextView 不显示在带有 RecycleView 的 LinearLayout 内
- javascript - 使用把手显示嵌套评论的最佳方法?
- windows - 哪种技术可以定位许多相似的基指针地址(快速)?
- ffmpeg - 使用 FFMPEG 分割视频时发出警告
- excel - 具有多个条件、多个结果和通配符的 Index/Small
- r - 涉及分类变量的 LASSO 子集选择