gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:41:14 26 4
gpt4 key购买 nike

为了说明,我有以下类型:

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

我想 malloc outer,然后初始化 inner 以获得 outer.i.c 的正确常量行为。

例如,类似的东西

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 %d\n", o->i.c, o->i.x, o->y);

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

printf("after: %d %d %d\n", o->i.c, o->i.x, o->y);

return 0;
}

请注意,这是一个比学术上更实用的解决方案,因此有些人可能想为此向我扔几个臭鸡蛋。

关于c - 使用 const 成员初始化嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10637027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com