簡體   English   中英

使用const成員初始化嵌套結構

[英]Initializing a nested struct with const members

我有以下類型,例如:

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

我想要malloc outer ,然后,稍后初始化inner以獲得outer.ic的正確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 };

但這給了我一個關於assignment of read-only member 'i'的錯誤,因為它是一個賦值,而不是初始化。

有沒有辦法做這樣的事情,這是編譯器的前期? 讓我們考慮使用*((int *) &o->ic)拋棄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;
}

請考慮到這是一個比學術上更實際的解決方案,因此有些人可能會想要給我一些爛雞蛋。

我可能會這樣做:

struct outer_init {
  struct inner_init {
    int c;
    int x;
  } i;
  int y;
};

struct outer_init *oi = malloc(sizeof *oi);
oi->y = find_y();
oi->i.c = find_c();
oi->i.x = find_x();

struct outer *o = (struct outer *)oi;

我不完全確定它絕對是便攜式的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM