I am wondering if there is reliable and standard-compliant way to copy only memberes from certain position in struct. For example something like this
struct A {
char* baz;
int foo;
int bar;
};
void copy(struct A* dst, const struct A* src) {
dst->baz = malloc(1 + strlen(src->baz));
strcpy(dst->baz, src->baz);
memcpy(
((void*)dst) + sizeof(char*),
((void*)src) + sizeof(char*),
sizeof(struct A) - sizeof(char*)
);
}
Is this valid C and does not violate the standard? I know there may be some issues with memory alignment sometimes, I don't know if it applies to this scenario.
Second question is - how to do it when skipping more than one member because the padding issues start to rear their ugly heads then
memcpyeach member individually, or the whole struct. Everything else will be UB, because of padding.offsetoffor start andsizeof-offsetoffor length, would that be UB?offsetofis still compiler dependent, and does not work in all cases (for example not for bitfields). For your simple example it would actually work, but I recommend just copying the whole struct and replace the changed members.