I have a C library (I'm using it in C++) that defines a struct and a function to operate on it.
struct s {
type1 x1;
type2 x2;
type3 x3;
type4 x4;
type5 x5;
};
void f(s* x);
I know that f
doesn't do anything involving s::x4
or s::x5
. Since both of them are useless for my purpose, and I have a lot of instances of s
, I'd like to allocate them in an array that packs them so that s[n+1]
starts right after s[n].x3
. Would doing something like the following result in undefined behavior? Assume that x4
and x5
are never used.
struct s_trimmed {
type1 x1;
type2 x2;
type3 x3;
};
size_t num_s = 1000;
char *mem = new char[stuff_before + num_s*sizeof(s_trimmed) + stuff_after];
for (size_t i=0; i<nums; ++i)
f((s*)(mem + stuff_before + i*sizeof(s_trimmed)));
mem
is a char
array, because it's just a chunk of memory, and I want other things to be in it besides the instances of s
.