disregard: sizeof struct returning unexpected results

Discussion in 'C Programming' started by Sean, Aug 20, 2004.

  1. Sean

    Sean Guest

    I perused the archives of comp.lang.c and found some answers related
    to addressability of struct elements (only in arrays?), and will
    probably proceed by using byte or char arrays filled with raw data and
    then converting to the expected types. Unless anyone has any helpful
    or enlightening comments, I will leave this issue closed for now.

    Thanks again for the time!
    Sean, Aug 20, 2004
    1. Advertisements

  2. Sean

    Jack Klein Guest

    No, it has nothing at all to do with whether you define a single item
    of a type or an array of them. The distance between one member of an
    array of type T and the next is sizeof(type T), and the size of a
    free-standing object of type T is also sizeof(type T).

    Using an array of unsigned chars is a good idea, but be careful about
    "converting" to the "expected" types. On some platforms the alignment
    imposed by the compiler is required by the underlying processor
    hardware, and violating it can have serious consequences.

    Assuming sizeof(short) is 2 and sizeof(int) is 4, then you could use
    something like this to pass the data around:

    unsigned char data [6];

    But this is a bad idea:

    unsigned short us;
    unsigned int ui;
    unsigned char data [6];

    /* get data into 'data' */

    us = *(unsigned short *)data;
    ui = *(unsigned long *)(data + 2);

    ....on some processors this produces code that runs more slowly but
    correctly. On others, including newer RISC architectures, either you
    get the wrong value or a hardware trap that terminates the program.

    The safe way to transfer the data is:

    memcpy(&us, data, 2);
    memcpy(&ui, data + 2, 4);
    Jack Klein, Aug 21, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.