Thread: Structure Padding in C

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    53

    Structure Padding in C

    Code:
    struct student
    { 
           int a;
           char c;
    }s1;
    Actual size of the above structure is 3 bytes(lets say int is 2 bytes).

    Is the declaration of above structure is correct or not as I didn't add any padding bytes?
    Is the structure padding the compiler dependent?

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    You should not add padding bytes, let the compiler deal with that. It will decide where to put the padding so that your variables are correctly aligned on 2, 4 or 8 byte boundaries depending on the compiler/OS you are working with.

    BTW... if ints in your compiler actually are 2 bytes, you seriously need to look into updating. The code it produces won't run on a 64 bit operating system.

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    53
    Thank u very much tater....

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by karthik537 View Post
    Is the declaration of above structure is correct or not as I didn't add any padding bytes?
    It's fine, you don't have to pad yourself unless you have a reason to do so.

    Is the structure padding the compiler dependent?
    Yes. With most compilers, you can also ask for no padding. Eg, with gcc:

    Code:
    struct student
    { 
           int a;
           char c;
           #pragma pack(1)
    }s1;
    Will ensure the struct is exactly sizeof(int) + sizeof(char).
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C Structure Padding
    By audinue in forum C Programming
    Replies: 20
    Last Post: 07-12-2011, 10:14 PM
  2. Structure padding
    By ShashiKantSuman in forum C Programming
    Replies: 4
    Last Post: 05-03-2011, 07:50 AM
  3. Structure padding
    By MK27 in forum C Programming
    Replies: 4
    Last Post: 12-15-2009, 02:25 PM
  4. Padding in Structure
    By ganesh bala in forum C Programming
    Replies: 11
    Last Post: 01-29-2009, 09:25 PM
  5. Detecting Structure Padding
    By johnnie2 in forum C++ Programming
    Replies: 2
    Last Post: 03-17-2003, 10:25 AM