为嵌套结构指针分配内存

我正在使用C代码生成器创建具有以下结构的头文件:

typdef struct Place { struct Forest { int trees; } *Forest; } Place ; 

并在c ++项目中使用它们。

当我尝试访问Place.Forest-> trees时,我得到一个段错误,因为Place.Forest是一个悬空指针。

我无法正确malloc它因为Place.Forest = malloc(sizeof(Place.Forest)); 只会返回指针的大小。

我不能使用Place.Forest=malloc(sizeof(struct Forest)); 因为我从C ++访问Place并且作用域使我无法看到Forest。

如何在不更改Place或un-nesting Forest的情况下为Forest分配内存?

由于自动生成大量代码,因此修改结构是不切实际的。

Forest分配内存就像这样。

  Place.Forest=malloc(sizeof(struct Forest)); 

它会将内存分配为该结构的大小。

经过几个小时的拧紧,我找到了解决方案。

您必须使用extern C来使编译器使用C样式链接,但您还必须使用C ++的作用域解析::来正确地解析结构类型。

头文件:

 #ifdef __cplusplus extern "C" { #endif typdef struct Place { struct Forest { int trees; } *Forest; } Place ; #ifdef __cplusplus } #endif 

程序:

 #include  #include  extern "C" { static void allocateForest(Place *p){ p->Forest = (struct Place::Forest *)malloc(sizeof(struct Place::Forest)); } } int main(void){ Place p; allocateForest(&p); p.Forest->trees = 1; std::cout << p.Forest->trees << std::endl; return 0; } 
 Place.Forest = malloc(sizeof(Place.Forest)); 

应该

 Place.Forest = malloc(sizeof(struct Forest)); 

因为你看到Forest是指向你的结构的指针而且sizeof(pointer)不是你想要的东西是sizeof(struct Forest)

在C中,嵌套的struct在整个程序中是可见的,因此嵌套它们没有意义。 只需单独定义它们(并使用typedef这样您就不必每次都编写struct x

 typedef struct { int trees; } Forest; typedef struct { Forest *forest; } Place; 

现在你可以写

 malloc(sizeof(Forest)); 

你应该为指针分配内存,否则它们是NULL。 用这个 :

 Place.Forest = (struct Forest*) malloc(sizeof(struct Forest)); 

另一件事:不要将变量命名为typedef。