Thread: Size of structure in bytes

  1. #1
    Registered User Micko's Avatar
    Join Date
    Nov 2003

    Size of structure in bytes

    Consider this code:
    #include <stdio.h>
    typedef struct element
    	char letter;
    	struct element* next;
    int main(void)
    	printf("Sizeof structure element is: %d bytes!",sizeof(element));
    If I compile this with Microsoft (Visual Studio .net) compiler and execute I get this result: Sizeof structure element is: 8 bytes!.

    But if I compile this with Borlan Turbo C compiler I get this:
    Sizeof structure element is: 3 bytes!.
    I'm using Win XP. I know that Turbo C was used under DOS. In TC sizeof(void*) is 2 bytes which means that it behaves like it is run under 16-bit operating system. Win XP is 32 bit OS and in TC is probably 16-bit application and that's why I get these results. Can you confirm this conclusion?

    What is interesting is somewhat unexpected result when using Visual Studio's compiler: 8 bytes and one could expect 5 bytes. Is that mean that structures can be only a multiple of 4. Why is that?

    Thanks for help!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Do a board search for "padding" and "alignment"
    Essentially, a compiler is free to add padding between members of a structure in order to ensure optimal alignment of data values within the structure.

    Now you can trade compactness of structures against run-time performance if you want to by using say "#pragma pack(1)" (or some other compiler-specific notation).

  3. #3
    Join Date
    Nov 2003
    It is aligning elements to the longword (32 bit) boundary because access is faster. On some 32-bit or 64-bit platforms misalignment of variables (not on a longword boundary) may result in a bus error. I believe Intel x86 systems are better off with a pointer on a longword boundary. I see the exact same thing on my PA RISC box.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Adventures in labyrinth generation.
    By guesst in forum Game Programming
    Replies: 8
    Last Post: 10-12-2008, 01:30 PM
  2. Problem referencing structure elements by pointer
    By trillianjedi in forum C Programming
    Replies: 19
    Last Post: 06-13-2008, 05:46 PM
  3. Heapsort
    By xENGINEERx in forum C Programming
    Replies: 2
    Last Post: 03-30-2008, 07:17 PM
  4. Invalid conversion from 'void*' to 'BYTE' help
    By bikr692002 in forum C++ Programming
    Replies: 9
    Last Post: 02-22-2006, 11:27 AM
  5. Changing a Structures Members array size
    By Xei in forum C++ Programming
    Replies: 1
    Last Post: 11-07-2002, 07:45 PM