Thread: a query on structure/union

  1. #1
    Registered User
    Join Date
    Jun 2002
    Posts
    3

    Unhappy a query on structure/union

    hi all,

    this may be a basic problem, but confusing me as a beginner.
    here follows a small piece of code :-

    struct ask
    {
    int a1;
    char ch[10];
    };

    int main()
    {
    ask z;
    cout<<"size of ask="<<sizeof(z)<<"\n";
    }

    it should result :-
    size of ask=14 (4 for int+10 for the array)
    but giving : 16
    I checked with sizeof(z.a1) which gives correctly 4.

    please clarify !

  2. #2
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    The structure is padded. This means that it is filled with junk data so as to be aligned on word boundries (32 bits -> 4 bytes, rounded up to the nearest number such that it mod 4 is 0). On some processors (x86) this helps performance, other processors (MIPS, or so I hear) simply refuse to run things not word-aligned.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  3. #3
    Registered User
    Join Date
    Jun 2002
    Posts
    3
    thanx silent strike for response !
    can u plz clarify a bit ?
    I'm giving u some piece of code with outputs I got :

    struct a
    {
    int x;
    char y;
    }v1;

    now,
    sizeof(v1.x) ---> gives 4
    sizeof(v1.y) ---> gives 1
    sizeof(v1) -----> gives 8 ( ?)

    why extra 3 bytes?

    again,
    union a
    {
    int x;
    char y[10];
    }v1;

    now,
    sizeof(v1.x) ---> gives 4
    sizeof(v1.y) ---> gives 10
    sizeof(v1) -----> gives 12( but, should be 10bytes , no ?)

  4. #4
    Registered User
    Join Date
    Jun 2002
    Posts
    3
    thanx SilentStrike again,
    got it.
    only initialization of structure members will do !

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. query problem
    By arian in forum C# Programming
    Replies: 1
    Last Post: 08-18-2008, 01:49 PM
  2. Url query encoding/decoding
    By Niara in forum Networking/Device Communication
    Replies: 6
    Last Post: 04-25-2007, 03:30 PM
  3. DNS Query
    By Simpsonia in forum Networking/Device Communication
    Replies: 1
    Last Post: 04-24-2006, 12:42 AM
  4. dns query
    By bulldog in forum C Programming
    Replies: 6
    Last Post: 02-24-2004, 10:44 AM
  5. O/l db and query interface
    By iain in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 08-29-2001, 11:56 AM