Mislab
Mislab

Reputation: 53

Copy byte array to not aligned structure

Hello trying to understand, why copying byte array to not aligned structure byte by byte i loose some data. Maybe there is a way how to solve it ?

enter image description here

Sample code bellow:

typedef struct {  //Not aligned data
    uint32_t val0;
    uint8_t  val1; 
    uint16_t val2;
    uint32_t val3;
}TestSt_t; 

TestSt_t testSt;
uint8_t testData[16] =  {
    0x11, 0x22, 0x33, 0x44,
    0x55,
    0x66, 0x77,
    0x88, 0x99, 0xAA, 0xBB
};
int main() {
    memcpy((uint8_t*)&testSt, (uint8_t*)&testData[0], sizeof(testSt));
}

enter image description here

Upvotes: 2

Views: 83

Answers (1)

tuket
tuket

Reputation: 3941

The compiler is adding a byte of padding

typedef struct {  //Not aligned data
    uint32_t val0;
    uint8_t  val1; 
        uint8_t padding;
    uint16_t val2;
    uint32_t val3;
}TestSt_t; 

So 0x66 is in that padding byte.

Upvotes: 2

Related Questions