c++ - 如何为结构数组分配内存?
问题描述
我有一个 C++ 库(实际上是另一个 C++ 库的包装器),我需要将一些struct
s 传递给我的 C 应用程序。
我不知道如何动态分配内存。
我得到一个分段错误。
图书馆.h
struct my_substruct {
unsigned char id ;
time_t date ;
char *info ;
};
typedef struct my_substruct My_substruct ;
struct my_struct {
char *description ;
unsigned char value ;
My_substruct *substruct ;
};
typedef my_struct My_struct ;
图书馆.cpp
unsigned char getStructs(My_struct *structs)
{
vector <structCPPLibrary> structsCPPLibrary = getFromCPPLibrary();
unsigned char numStructs = structsCPPLibrary.size();
structs = (My_struct *)malloc(numStructs*sizeof(My_struct));
unsigned char indexStruct = 0;
for (auto s : structsCPPLibrary)
{
structs[indexStruct].description = (char *)malloc(s.description.size() + 1);
strcpy(structs[indexStruct].description, s.description.c_str()); // In 's' is a std::string
structs[indexStruct].value = s.value; // In 's' is an unsigned char too
unsigned char numSubstructs = s.substructs.size(); // In 's' is a vector of Substructs
structs[indexStruct].substruct = (My_substruct *)malloc(numSubstructs*sizeof(My_substruct));
unsigned char indexSubstruct = 0;
for (auto sub : s.substruct) {
structs[indexStruct].substruct[indexSubstruct].id = sub.id; // In 'sub' is an unsigned char too
structs[indexStruct].substruct[indexSubstruct].date = sub.date; // In 'sub' is a time_t too
structs[indexStruct].substruct[indexSubstruct].info = (char *)malloc(sub.info.size() + 1);
strcpy(structs[indexStruct].substruct[indexSubstruct].info, sub.info.c_str()); // In 'sub' is a std::string
indexSubstruct++;
}
indexStruct++;
}
return indexStruct;
}
主程序
void getStructFromWrapper(void)
{
My_struct *structs;
unsigned char numStruct = getStructs(structs);
show_content(structs);
}
解决方案
改变
unsigned char getStructs(My_struct *structs) {
...
}
getStructs(structs);
至
unsigned char getStructs(My_struct **p_structs) {
// C function can't be pass by reference, so convert to a reference here
auto& struct = *p_structs;
...
}
...
getStructs(&structs);
您的问题是您的struct = ...
行没有修改structs
in的值getStructFromWrapper
。
推荐阅读
- javascript - ReferenceError:未定义通道
- excel - VBA 用户表单代码仅在工作表可见时才有效
- angular - Angular 9 取消 HTTP 请求
- kubernetes - 预检 (OPTIONS) 返回 403,CORS
- python - 使用 meshlabxml remiss.simplify 进行网格简化
- amazon-elasticache - 如何检查 AWS Elasticache(REDIS) 中的 if config 命令名称是否已更改
- javascript - 自定义类型作为函数:从 JavaScript 中的另一个命名函数构造函数
- kubernetes - 在 Gcp 中使用 helm 安装 ibm mq chart 版本 1.2.0,在创建 Pod 时出现错误“Creashloopbackoff”
- postgresql - Postgres9.5 分区
- .htaccess - 使用 .htaccess 将特定页面阻止到 Pinterest