structures

This is a discussion on structures within the C Programming forums, part of the General Programming Boards category; i hv got a doubt with this program. struct emp { int eno; char ename[10]; }; main(){ printf("%d\n",sizeof(int)); printf("%d\n",sizeof(char[10])); printf("%d\n",sizeof(struct ...

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    1

    Post structures

    i hv got a doubt with this program.

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

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

    4
    10
    16

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

    pl advise.

    Prasad

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,532
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21