Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a struct to char array using memcpy

Tags:

c++

arrays

c

struct

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

like image 328
CSharper Avatar asked Oct 20 '15 06:10

CSharper


2 Answers

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).

like image 122
ThBB Avatar answered Nov 11 '22 03:11

ThBB


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.

like image 1
FrancTheTank Avatar answered Nov 11 '22 02:11

FrancTheTank