为嵌套结构指针分配内存 [英] Allocating memory for nested structure pointer
问题描述
我正在使用C代码生成器来创建具有以下结构的头文件:
I am using a C code generator that is creating header files with following structures:
typdef struct Place {
struct Forest {
int trees;
} *Forest;
} Place ;
并在c ++项目中使用它们.
And using them in a c++ project.
当我尝试访问Place.Forest->树时,我遇到了段错误,因为Place.Forest是一个悬空的指针.
When I try to access Place.Forest->trees, I get a segfault because Place.Forest is a dangling pointer.
我无法正确分配它,因为
Place.Forest = malloc(sizeof(Place.Forest));
只会返回指针的大小.
I can't properly malloc it because
Place.Forest = malloc(sizeof(Place.Forest));
will just return the size of the pointer.
我不能使用
Place.Forest=malloc(sizeof(struct Forest));
因为我正在从C ++访问Place,并且范围限制使我无法看到Forest.
I can't use
Place.Forest=malloc(sizeof(struct Forest));
Because I am accessing Place from C++ and scoping prevents me from being able to see Forest.
如何在不更改位置或取消嵌套森林的情况下为森林分配内存?
How do I allocate memory for Forest without changing Place or un-nesting Forest?
由于要自动生成大量代码,因此无法修改结构.
Modifying the structures is impracticable due to the large amount of code that is being automatically generated.
推荐答案
经过几个小时的摸索,我找到了解决方案.
After several hours of screwing around, I found a solution.
您必须使用extern C
来使编译器使用C样式链接,但还必须使用C ++的作用域分辨率::
来正确解析结构类型.
You have to use extern C
to get the compiler to use C style linking, but you also have to use C++'s scope resolution ::
to correctly resolve the structure type.
头文件:
#ifdef __cplusplus
extern "C" {
#endif
typdef struct Place {
struct Forest {
int trees;
} *Forest;
} Place ;
#ifdef __cplusplus
}
#endif
程序:
#include <stdlib.h>
#include <iostream>
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;
}
这篇关于为嵌套结构指针分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!