Thread: size of struct

  1. #1
    Unregistered
    Guest

    Unhappy size of struct

    struct ip {
    unsigned char ip_length:4;
    unsigned char ip_version:4;
    unsigned char ip_tos;
    unsigned short ip_total_length;
    unsigned short ip_id;
    unsigned short ip_flags;
    unsigned char ip_ttl;
    unsigned char ip_protocol;
    unsigned short ip_cksum;
    unsigned int ip_source;
    unsigned int ip_dest;
    };

    please can anyone please tell why the size of the struct is 24 bytes though if i take ip_length:4 and ip_version:4 out from the structure still the size remains the same .

    i tried playing with the structure a lot and am not sure why the size of 2 integers and one char is 12 bytes

    thanx
    rohit

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    structures are normally padded so that they fit on paragraph boundaries in memory.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    752
    Fields can only be declared as ints... although if this is something that's giving your compiler pains, I assume it would give a warning.
    Callou collei we'll code the way
    Of prime numbers and pings!

  4. #4
    Unregistered
    Guest
    thanx but i need to define the ip structure field exactly as of 20 bytes but if i use

    unsigned int version:4;
    unsigned int length:4;

    then the structure size goes to 24 bytes but if i use the char then it's ok ...


    the structure is quite like the same as in <netinet/ip.h> in linux .the same is 20bytes in size in linux too for a similar structure .

    i dunno why the compiler is making such a difference when both the OS are 32 bit .

  5. #5
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,130
    >i need to define the ip structure field exactly as of 20 bytes

    Then you have to lookup your compiler specifications in your helpfile. You need to turn of structure padding.
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  2. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  3. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM
  4. Replies: 11
    Last Post: 03-25-2003, 05:13 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM