【问题标题】:Allocating memory for nested structure pointer为嵌套结构指针分配内存
【发布时间】:2015-03-27 05:27:19
【问题描述】:

我正在使用 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 或取消嵌套 Forest 的情况下为 Forest 分配内存?

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

【问题讨论】:

    标签: c++ c pointers struct nested


    【解决方案1】:

    要为Forest 分配内存,请这样做。

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

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

    【讨论】:

    • 如果我访问 Place 的项目是 C++,这仍然有效吗?我虽然范围界定会干扰。
    • 他说得对,我明白了:error: invalid application of ‘sizeof’ to incomplete type ‘main()::Forest’
    • 抱歉,我对c++一无所知。
    【解决方案2】:

    经过几个小时的折腾,我找到了解决办法。

    您必须使用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;
    }
    

    【讨论】:

      【解决方案3】:
      Place.Forest = malloc(sizeof(Place.Forest));
      

      应该是

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

      因为如您所见,Forest 是指向您的结构的指针,而 sizeof(pointer) 不是您要查找的内容,您想要的是 sizeof(struct Forest)

      【讨论】:

      • 如果我从 C++ 访问 Place,这会起作用吗?我虽然范围界定会干扰。
      • @charlesw 如果您有 malloc() 定义,那么是的,您将在堆上为此调用分配内存
      【解决方案4】:

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

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

      现在你可以写了

      malloc(sizeof(Forest));
      

      【讨论】:

      • 不幸的是,修改结构不是我的选择。它们是自动生成的,有数百个。此外,如果必须重新生成它们,则必须一次又一次地进行更改。
      【解决方案5】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-22
        • 2023-04-02
        • 2017-01-03
        • 2021-12-11
        相关资源
        最近更新 更多