加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用const成员初始化嵌套结构

发布时间:2020-12-16 06:59:56 所属栏目:百科 来源:网络整理
导读:我有以下类型,例如: struct outer { struct inner { const int c; int x; } i; int y;}; 我想要malloc外部,然后,初始化内部以获得outer.i.c的正确const行为. 例如,像 struct outer *o = malloc(sizeof *o);o-y = find_y();int cc = find_c();int xx = find_
我有以下类型,例如:

struct outer {
  struct inner {
    const int c;
    int x;
  } i;
  int y;
};

我想要malloc外部,然后,初始化内部以获得outer.i.c的正确const行为.

例如,像

struct outer *o = malloc(sizeof *o);
o->y = find_y();
int cc = find_c();
int xx = find_x();
o->i = { .c = cc,.x = xx };

但这给了我一个关于只读成员’i’的分配的错误,因为它是一个赋值,而不是初始化.

有没有办法做这样的事情,这是编译器的前期?让我们考虑使用*((int *)& o-> i.c)抛弃const或使用& o.i上的memcpy作为偷偷摸摸的编译器.我可以得到他们需要的位,但我正在寻找最不实际的方法来做到这一点.

我没有使用C(我正在使用C99).

解决方法

唯一真正不变的东西是驻留在只读内存中的东西. Malloc / calloc永远不会给你只读内存.所以“const”就是谎言.嗯,这是编译器和开发人员的提示.我不确定C99中是否有任何语法糖来解决某些可能对某人来说似乎有问题的问题,但我会这样做:

#include <stdio.h>
#include <stdlib.h>

struct outer {
    struct inner {
        const int c;
        int x;
    } i;
    int y;
};

int main(void)
{
    struct outer    *o;

    o      = calloc(1,sizeof(struct outer));

    printf("before: %d %d %dn",o->i.c,o->i.x,o->y);

    *((int *)&o->i.c) = 1;
    o->i.x = 2;
    o->y = 3;

    printf("after: %d %d %dn",o->y);

    return 0;
}

请考虑到这是一个比学术上更实际的解决方案,因此有些人可能会想要给我一些烂鸡蛋.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读