c - 如何在c中创建嵌套结构

标签 c struct

我已经开始学习 C,我发现创建复杂的数据结构非常具有挑战性!

这是背景:

我在头文件 foo.h 中创建了一个 struct 并将其内容公开:

struct frame {
     char *name;
     int width;
     int height;
     //other stuffs
}

extern const struct frame
     vid_1080p,
     vid_720p;

frame 的实例是常量,可以从其他 c flies 访问。 foo.c 看起来像这样:

const struct frame vid_1080p = {
    .name                 = "1080p",
    .width                = 1920,
    .height               = 1080,
};
const struct frame vid_720p = {
    .name                 = "720p",
    .width                = 1280,
    .height               = 720,
};

我想在 struct frame 中创建另一个 struct ,其中的元素将在我的程序启动时计算,并且可以在必要时修改它。我不确定如何处理这个问题,我在下面尝试过这种方法但它不起作用。

我失败的方法:

我修改了foo.h:

struct frame_calc {
     int ratio;
     //other stuffs
}

struct frame {
     char *name;
     int width;
     int height;
     //other stuffs
     struct frame_calc *calc;
}

并且foo.c也被修改:

 const struct frame vid_1080p = {
        .name                 = "1080p",
        .width                = 1920,
        .height               = 1080,
        .calc                 =  malloc(sizeof(struct frame_calc)) //compiler complains here
    };
    const struct frame 720p = {
        .name                 = "720p",
        .width                = 1280,
        .height               = 720,
        .calc                 =  malloc(sizeof(struct frame_calc))
    };

然后 init() 在我的程序开始时被调用一次,它填充了 calc 结构:

void init(void)
{
     vid_1080p.calc.ratio = vid_1080p.height / vid_1080p.width;
     vid_720p.calc.ratio  = vid_720p.height  / vid_720p.width;
}

这种方法给我带来了一些编译器错误。我也不确定如何适本地初始化我的嵌套结构。另一个问题是,我正在使用 malloc,这意味着我需要在正确的地方释放它。我想避免这种情况。我相信所有的 pro c 程序员都知道如何更好地解决这个问题!

最后一个问题,如何从其他 c 文件访问 vid_1080p 实例的这个 ratio 成员?我在想 vid_1080p->frame->calc->ratio

希望我已经设法解释了我想做什么?如果没有,鉴于这是我的第一个问题,我将不胜感激关于如何在 StackOverflow 中更好地修改这个问题的建设性批评!

最佳答案

您不需要 malloc calc 成员,因为嵌入了一个实际实例 - 它不是指针。

如果出于某种原因你需要它成为一个指针,那么你需要:

struct frame {
     ...
     struct frame_calc* calc;
}

访问将是 var.calc->ratio = something;

如果您尝试在创建后修改结构(通过 init()),为什么结构是 const?您是否试图通过让结构保存一个指针来解决 const struct 问题,这样您就不必更改指针但可以更改它指向的值?

我建议不要使用 const 结构:

struct frame vid_1080p {
    ...
}

然后您的 init 函数可以执行 vid_1080p.calc.ratio = vid_1080p.height/vid_1080p.width; 如果您真的想通过指针强制执行常量访问结构到一个 const 结构。 常量帧 *p_1080p

关于c - 如何在c中创建嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53367706/

相关文章:

c - 为什么 sizeof() 返回 4 个字节而不是 2 个字节的短整型?

c++ - 为类成员函数的结构输入设置默认值

c++ - 为什么我的 vector 不能访问嵌套结构中的变量?

json - 使用任意键/值对解码 JSON 以构造

c++ - 与内存映射、c++、ERROR_NOT_ENOUGH_MEMORY 共享结构

c - 为什么 char 与 signed char 或 unsigned char 不兼容?

c - 类型限定符如何从合格到不合格排序?

c - 如果用户在 scanf 中输入字符来查找整数,如何避免死循环?

c++ - 在结构中声明常量变量导致我出现此错误非静态成员引用必须相对于特定对象

c - 介子构建 : How to define dependency to a library that cannot be found by `pkg-config` ?