What mistake I am doing here in C code

I wrote following code


typedef union
{
    struct
    {
        int8_t   a;
        int16_t  b;
        uint32_t c;
    };

    int8_t my_arr[7];
}x;

uint8_t arr[7];

int main( void )
{
    uint32_t i;
    x *y;

    for( i = 0 ; i < 7 ; i++ )
    {
        arr[i] = i + 2 * 5;
    }

    y = ( x* )arr;

    i = y->a;
    i = y->b;
    i = y->c;
}



End result in Y is:
a = 0x0a;
b = 0x0d0c
c = 0x00100F0E
my_arr[0-7] = 0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10;

& array conatisn
arr[0-7] = 0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10;

My question is when a= 0x0a , then should be b = 0x0c0b & c = 0x100f0e0d
but this is not the case

I am using keil 4.70.0.0, mdk arm

Parents
  • Try PACK Compiler Directive

    Default PACK(2)

    The PACK directive causes the compiler to generate byte-aligned or half-word-aligned structures. This is useful when exchanging data with other systems where no alignment is required.

    Example

    #pragma pack(1)     /* byte alignment */
    #pragma bytealign   /* ptrs to byte-aligned objects */
    
    struct s1  {
      int  i1;     // i1 has offset 0
      char c1;     // c1 has offset 2
      int  i2;     // i2 has offset 3
      char c2;     // c2 has offset 5
      int  i3;     // i3 has offset 6
      char z1;     // z1 has offset 8
    };
    
    
    #pragma pack()    /* reset to default alignment */
    
    struct s2  {
      int  i1;     // i1 has offset 0
      char c1;     // c1 has offset 2
      int  i2;     // i2 has offset 4
      char c2;     // c2 has offset 6
      int  i3;     // i3 has offset 8
      char z1;     // z1 has offset 10
    };
    
    

Reply
  • Try PACK Compiler Directive

    Default PACK(2)

    The PACK directive causes the compiler to generate byte-aligned or half-word-aligned structures. This is useful when exchanging data with other systems where no alignment is required.

    Example

    #pragma pack(1)     /* byte alignment */
    #pragma bytealign   /* ptrs to byte-aligned objects */
    
    struct s1  {
      int  i1;     // i1 has offset 0
      char c1;     // c1 has offset 2
      int  i2;     // i2 has offset 3
      char c2;     // c2 has offset 5
      int  i3;     // i3 has offset 6
      char z1;     // z1 has offset 8
    };
    
    
    #pragma pack()    /* reset to default alignment */
    
    struct s2  {
      int  i1;     // i1 has offset 0
      char c1;     // c1 has offset 2
      int  i2;     // i2 has offset 4
      char c2;     // c2 has offset 6
      int  i3;     // i3 has offset 8
      char z1;     // z1 has offset 10
    };
    
    

Children
More questions in this forum