Thread: How to avoid Structure Padding in C?

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    129

    How to avoid Structure Padding in C?

    Code:
    #include <stdio.h>
    
    struct point
    {
        int x;
        char y;
        float z;
    }var;
    
    
    int main()
    {
        printf("size of structure = %d", sizeof(var));
    
    
        return 0;
    }
    size of structure = 12

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Lookup the pragmas for your compiler.

    For some simple compilers the order will make a difference. Put the biggest items first. As in.
    Code:
    struct point
    {
        float z;
        int x;
        char y;
    }var;
    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > size of structure = 12
    With those three members, it's always going to be 12 no matter how you arrange them.

    If you succeed in making it 9 through some pragma, then the compiler will generate very sub-optimal code, because it will have to assume that both the int and float are unaligned. In doing so, it will read each one a byte at a time in order to construct a properly aligned temporary.

    Be careful what you're saving.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Structure padding
    By Satya in forum C Programming
    Replies: 2
    Last Post: 05-29-2015, 07:35 AM
  2. C Structure Padding
    By audinue in forum C Programming
    Replies: 20
    Last Post: 07-12-2011, 10:14 PM
  3. Structure Padding in C
    By karthik537 in forum C Programming
    Replies: 3
    Last Post: 06-15-2011, 07:10 AM
  4. Structure padding
    By ShashiKantSuman in forum C Programming
    Replies: 4
    Last Post: 05-03-2011, 07:50 AM
  5. Padding in Structure
    By ganesh bala in forum C Programming
    Replies: 11
    Last Post: 01-29-2009, 09:25 PM

Tags for this Thread