Thread: structures

  1. #1
    Registered User
    Join Date
    Apr 2002

    Post structures

    i hv got a doubt with this program.

    struct emp {
    int eno;
    char ename[10];
    printf("%d\n",sizeof(struct emp));

    I work on ANSI C in SuSE-Linux and i get the following output:


    how come that the size of the structure is occupying two bytes extra.

    pl advise.


  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Each type in C also has an alignment. The alignment determines the valid memory addresses which can be used to access that type.

    For chars, this is 1, and therefore any address will do.

    For ints, the alignment could be say 2, which would constrain ints to always be on even addresses.
    Why do this?
    1. some machines are more efficient when they access data which is on aligned memory boundaries
    2. some machines simply refuse to access mis-aligned data, and generate protection faults (SIGBUS on unix)

    To answer your question, structures are padded to ensure that each member of the structure is on its alignment boundary, and the whole struture is padded to ensure that arrays of the structure remain aligned.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. Structures, passing array of structures to function
    By saahmed in forum C Programming
    Replies: 10
    Last Post: 04-05-2006, 11:06 PM
  3. Input output with structures
    By barim in forum C Programming
    Replies: 10
    Last Post: 04-27-2004, 08:00 PM
  4. pointers to arrays of structures
    By terryrmcgowan in forum C Programming
    Replies: 1
    Last Post: 06-25-2003, 09:04 AM
  5. Methods for Sorting Structures by Element...
    By Sebastiani in forum C Programming
    Replies: 9
    Last Post: 09-14-2001, 12:59 PM