Search code examples
carraysmemorystructurecopying

Copying array to a structure


I have an array of 9 bytes and I want to copy these bytes to a structure :

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct _structure {
    char one[5];        /* 5 bytes */
    unsigned int two;   /* 4 bytes */
} structure;

int main(int argc, char **argv) {

    structure my_structure;

    char array[]    = {
        0x41, 0x42, 0x43, 0x44, 0x00,   /* ABCD\0 */
        0x00, 0xbc, 0x61, 0x4e          /* 12345678 (base 10) */
    };

    memcpy(&my_structure, array, sizeof(my_structure));

    printf("%s\n", my_structure.one);   /* OK, "ABCD" */
    printf("%d\n", my_structure.two);   /* it prints 1128415566 */

    return(0);
}

The first element of the structure my_structure, one, is copied correctly; however, my_structure.two contains 1128415566 while I expect 12345678. array and my_structure have different sizes and even if they are equal in size, still there will be a problem with two . How can I fix this issue?


Solution

  • As Mysticial already explained, what you're seeing is the effect of structure alignment - the compiler will align elements on boundaries of its word size, ie in 32 bits code on 4-byte boundaries, effectively leaving a gap of 3 bytes between the char[5] and the next element.

    If you use gcc or Visual Studio, #pragma pack(1) allows you to override the "preferred" packing the compiler would use by default - in this example you instruct the compiler to instruct on 1-byte boundaries, ie without "holes". This is often useful in embedded systems to map blocks of bytes onto a structure. For other compilers consult your compiler manual.