Convert structure to char array using memcpy

I am trying to convert the following structure to a char array so that I can send it through 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" , '#'}; 

Then I 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 final values ​​in a char array

 0x0A 0xFF 

Initially, I thought it was getting values, because when I passed it to a char array, it effectively cast it to a string, so although it was NULL '\ 0'

Any help would be appreciated.

thanks

+5
source share
2 answers

I have a suspicious suspicion that you are using an 8-bit microcontroller! You can debug printing b[sizeof(foo)] and b[sizeof(foo)+1] These will be your two characters. If you notice, you should not reference them, they are outside of your char array. for example, n an array of elements [0 .. (n-1)] (copied from your structure)

If you add an unused element to your structure (or increase the size of your final member), the char array may be interrupted by the "\ 0" compiler, probably wants to do this.

Or assign a pointer, as @Melebius showed.

+1
source

In modern processors, sizeof (loading structure data) needs to be aligned at 32-bit boundaries. The size of your data structure is 8 characters + 1 short (16 bit) integer. The compiler must add 2 characters to the size of the structure in order to be able to correctly process it when assigned. Since you are communicating on a serial line and know exactly what you are sending, you can also specify the exact number of bytes that you want to send on your serial lines: 2 + / * 1 short * / + 8 (8 bytes).

+4
source

Source: https://habr.com/ru/post/1234083/


All Articles