如何为结构数组分配内存?



我有一个C++库(实际上是另一个C++库的包装器(,我需要将一些struct传递给我的 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;
}

主.c

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 = ...行没有修改getStructFromWrapperstructs的值。

相关内容

  • 没有找到相关文章