So, I want to be able to write binary data in C that alternates between a single byte and a 32-bit signed integer, and have a struct type that can be used for this with pointer incrementing.
So far, this is my struct
struct MarkedInt
{
unsigned char mark;
int value;
};
And this is my code
void clean_obj(struct MarkedInt* mi)
{
mi->mark = 0;
mi->value = 0;
}
int main(void) {
struct MarkedInt a;
clean_obj(&a);
a.mark = 5;
a.value = 500;
unsigned char* printer = (unsigned char*)(&a);
printf("sizeof a is %lu\n", sizeof(a));
for(int i = 0; i< sizeof(a);i++)
{
printf("%u\n", printer[i]);
}
return 0;
}
However, the result of the program is this
sizeof a is 8
5
4
64
0
244
1
0
0
So it sets the size of my struct MarkedInt
at 8, making the mark member 4 bytes instead of 1. This causes some unwanted padding, where a pointer to the struct used to read binary data would be reading 8 bytes at a time and not 5.
My desired outcome is this
unsigned char buf[] = {/*mark*/ 5, /*int value*/ 1, 0, 0, 0};
struct MarkedInt* reader = buf;
printf(" mark: %u, value: %d\n", reader->mark, reader->value);
Is it possible to do this in c? Or is simply reading the byte marker and int separately recommended?