4

説明のために、次のタイプがあります。

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

私はmallocしたいのですがouter、後で初期化innerして、の正しいconst動作を取得し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 };

assignment of read-only member 'i'しかし、これは初期化ではなく割り当てであるため、エラーが発生します。

コンパイラーに事前にこのようなことをする方法はありますか?*((int *) &o->i.c)constをキャストしたり、memcpyを使用し&o.iてコンパイラーをこっそりと回したりするようなトリックを考えてみましょう。私はそれらが必要なところにビットを得ることができます、しかし私はこれをするための最も卑劣な方法を探しています。

私はC++を使用していません(C99を使用しています)。

4

2 に答える 2

1

本当に一定しているのは、読み取り専用メモリにあるものだけです。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;
}

これはアカデミックな解決策というよりも実用的な解決策であることを考慮してください。

于 2012-05-17T14:19:29.777 に答える
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;

ただし、完全に移植可能かどうかは完全にはわかりません。

于 2013-02-11T18:21:47.627 に答える