Thread: sizeof struct

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    27

    sizeof struct

    I'm running the following prog :

    Code:
    #include <iostream>
    
    using namespace std;
    
    struct customer {
        short number;       //   1:
        int postcode;         //   2:
    };
    
    int main() {
    
        cout<<sizeof(customer)<<endl;
    
    }
    If I run it with line 1 in comments the output is 4.OK for that.
    If I run it with line 2 in comments the output is 2.OK for that too.
    But if i run it as it is above the outout is 8.Why is that?

    Thank you in advance.

  2. #2
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    Because the compiler belives that aligning structs to 4- or 8-byte boundaries will make your program faster.
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  3. #3
    Registered User
    Join Date
    Feb 2003
    Posts
    596
    "Because the compiler belives that aligning structs to 4- or 8-byte boundaries will make your program faster."


    ???
    That doesn't explain why sizeof (customer) will return 2 if there is only 1 short int, or 6 if there are 3 short ints (and no ints), yet if there are 3 short ints plus 1 int, it returns 12.

    Does it align structs that way only when they contain ints?

  4. #4
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 06:55 PM
  2. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 01:04 PM
  3. Replies: 10
    Last Post: 05-18-2006, 11:23 PM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 06:58 PM