[英]Allocating memory for nested structure pointer
我正在使用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。
我如何在不更改位置或取消嵌套森林的情況下為森林分配內存?
由於要自動生成大量代碼,因此無法修改結構。
為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 <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;
}
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));
另一件事:不要將變量的名稱命名為typedefs。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.