struct abcd
 {
     char q;
     int w;
     //long int e;
 };

why size of this structure is 8 bytes and if i include long int e , size becomes 12 bytes?

Members of a structure may be aligned to certain byte boundaries to improve performance or if the platform simply doesn't allow an object of a certain type to begin at any byte. Also, and partially to facilitate alignment, there may be padding between members of a structure or at the end of the structure.

So unless you go out of your way to pack a structure (using non-portable methods), its size will likely be more than the sum of its members' sizes.

how performance is increased?
are structure elements location in memory contiguous? if yes, in this case then there is free memory blocks after char variable as size is greater than individual sum? correct me if i am wrong.

how performance is increased?

Values can be loaded into memory and registers more quickly when they're suitably aligned. Otherwise the system might have to calculate an offset from a native boundary to get to the correct address.

are structure elements location in memory contiguous?

Barring padding, yes.

if yes, in this case then there is free memory blocks after char variable as size is greater than individual sum?

In this case I'd wager that there are 3 bytes of padding after q so that w is properly aligned on a word boundary. So the structure looks like this in memory:

[q][?][?][?][w][w][w][w]

does that means that order in which i write the structures elements matter to calculate the offset and hence size changes?
also 3 bytes are free here.. isnt it memory wastage though small?

does that means that order in which i write the structures elements matter to calculate the offset and hence size changes?

Yes. My personal preference is to order members in a way that makes intuitive sense at a higher level than padding and alignment, but that's just a general guideline. I've been known to optimize the organization of my structures when the situation warranted it. ;)

also 3 bytes are free here.. isnt it memory wastage though small?

This is one of many places where you'll encounter the speed vs. space tradeoff. At the cost of a few bytes, the performance can be improved by a statistically significant amount.

Member Avatar for I_m_rude

there is padding after each element of structures so as to fit it in a boundary which is neccessary for a computer. it is done because while reading data, it has to take the offset and then read, so to save this time , padding is done ;) thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.