M
Michael Birkmose
Hi everyone,
I am in a situation where I need to instantiate a struct which has no tag
name:
struct some_struct {
struct {
int a;
} embedded_member;
};
I need to instantiate the embedded member in my application as a variable
it self - however that is not possible since there is no tag name for this
struct. Therefore I need to be able to do something like this
/* Struct with the same structure as the struct with no tag name */
struct hack {
int a;
} hack_instance;
struct some_struct st;
st.embeddeb_member = hack_instance;
However this gives an type error.
The solution I came up with is the following:
void hack_copy(void *dst, void *src, int size) {
memcpy(dst, src, size);
}
And then instead of st.embeddeb_member = hack_instancer; I do:
hack_copy(&st.embedded_member, &h, sizeof(struct hack));
I know that in this case I could just have done:
strut some_struct some_instance;
some_instance.embedded_member = 6;
However my application is a an application generating C code, and it would
be a problem to generate that sort of code (loong story
- the bottom
line is if this trick is possible the design of my application stays
very nice).
So my question is if this is a propper solution? I know that the type
struct hack, is a different type than the embedded struct, however they
should have the same representation in memory? The only thing I am in
doubt of is if there could be some alignment problems in some cases is the
structs contains different datatypes?
Cheers,
I am in a situation where I need to instantiate a struct which has no tag
name:
struct some_struct {
struct {
int a;
} embedded_member;
};
I need to instantiate the embedded member in my application as a variable
it self - however that is not possible since there is no tag name for this
struct. Therefore I need to be able to do something like this
/* Struct with the same structure as the struct with no tag name */
struct hack {
int a;
} hack_instance;
struct some_struct st;
st.embeddeb_member = hack_instance;
However this gives an type error.
The solution I came up with is the following:
void hack_copy(void *dst, void *src, int size) {
memcpy(dst, src, size);
}
And then instead of st.embeddeb_member = hack_instancer; I do:
hack_copy(&st.embedded_member, &h, sizeof(struct hack));
I know that in this case I could just have done:
strut some_struct some_instance;
some_instance.embedded_member = 6;
However my application is a an application generating C code, and it would
be a problem to generate that sort of code (loong story
line is if this trick is possible the design of my application stays
very nice).
So my question is if this is a propper solution? I know that the type
struct hack, is a different type than the embedded struct, however they
should have the same representation in memory? The only thing I am in
doubt of is if there could be some alignment problems in some cases is the
structs contains different datatypes?
Cheers,