I have the following types, for illustration:
struct outer {
struct inner {
const int c;
int x;
} i;
int y;
};
I want to malloc outer and then, later, initialize inner to get the right const behavior for outer.i.c.
For example, something like
struct outer *o = malloc(sizeof *o);
o->y = find_y();
int cc = find_c();
int xx = find_x();
o->i = { .c = cc, .x = xx };
but this gives me an error about assignment of read-only member 'i', because it's an assignment, not an initialization.
Is there a way to do something like this that's up-front to the compiler? Let's consider tricks like casting away const with *((int *) &o->i.c) or using memcpy on &o.i as sneaking around the compiler. I can get the bits where they need to be, but I am looking for the least sneaky way to do this.
I am not using C++ (I'm using C99).
struct outer *o = malloc(sizeof *o);is an initialisation, but that is only the pointer being initialised, not where it points at. So you need to explicitly assign o->i.c and o->i.x, or assign both of them in one sweep via a struct assignment (which can be using a "struct literal", since c99) .