size of structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

struct NODE
{
       int info;
       float next;
       char p;
};

int main()
{   
    printf("%d %d %d %d",sizeof(int),sizeof(float),sizeof(char),sizeof(NODE));
    getch();
}


output: 4 4 1 ?
what should be "?" ?
sizeof(NODE) will depend on your compiler. Why not run the program and see for yourself?
ofcrse i saw it..and its giving 12...so m confused that shudnt it be 4+4+1=9 instead of 12
Sometimes the compiler adds padding (unused bytes) to the structures. This is because it's often more efficient to access variables stored at certain boundaries.

For example, to store a 4 byte integer it might be more efficient to store it at a memory address that is a multiple of 4. If there was no padding and you create an array of NODE, assuming the array is placed on address 12, the first NODE in the array will have its int variable at the same memory address 12 (which is a multiple of 4). The second NODE in the array is placed placed at address 21 (12 + 9). Not good, 21 is not a multiple of 4. With padding the second NODE in the array will instead be placed at address 24, which is a multiple of 4.
Last edited on
okay.. that is something strange...it makes me think as if the compiler is a living being and not a programmed thing that it is capable of doing such random things...so this padding thing varies frm compiler to compiler ??and does it exist in best compilers?
The compiler tries to make the best use of the hardware. I don't think the padding differs much, or anything, between different compilers when compiled for the same hardware.
Topic archived. No new replies allowed.