I am trying to convert the following struct to a char array so that I can send it via the serial port.
struct foo
{
uint16_t voltage;
char ID ;
char TempByte;
char RTCday[2];
char RTCmonth[2];
char RTCyear[2];
char RTChour[2];
char RTCmin[2];
char Sepbyte;
}dvar = { 500, 'X' , '>' , "18" , "10" , "15" , "20" , "15" , '#'};
I then convert it to a char array using the following:
char b[sizeof(struct foo)];
memcpy(b, &dvar, sizeof(struct foo));
However for some reason I get these trailing values in the char array
0x0A 0xFF
I initially thought it was getting the values because when i cast it to a char array it was effectively casting it to a string so I though the was the NULL '\0'
Any help will be appreciated.
Thanks
On modern processors, sizeof(struct data download) needs to be aligned on 32bits boundaries. Your data structure size is 8 chars + 1 short (16 bits) integer. The compiler needs to add 2 chars to the size of the structure to be able to handle it correctly when assigning it. Since you're doing communication over a serial line and know exactly what you're sending, you might as well specify the exact number of bytes you're willing to send over your serial lines: 2 +/*1 short */ + 8 (8 bytes).
I have a sneaky suspicion you are using an 8bit microcontroller!
You can debug by printing b[sizeof(foo)]
, and b[sizeof(foo)+1]
These will be your two characters.
If you noticed, you should not be referencing these, they are outside the bounds of your char array. eg n element array [0..(n-1)] (copied from your struct)
If you add an unused element to your struct(or increase the size of your final member) the char array can be terminated '\0' -compiler probably wants to do this.
Or do a pointer assignment as @Melebius has shown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With