(sizeof) char always returns 1 in 32 bit GCC compiler.
But since the basic block size in 32 bit compiler is 4, How does char occupy a single byte when the basic size is 4 bytes???
Considering the following :
struct st
{
int a;
char c;
};
sizeof(st) returns as 8 as agreed with the default block size of 4 bytes (since 2 blocks are allotted)
I can never understand why sizeof(char) returns as 1 when it is allotted a block of size 4.
Can someone pls explain this???
I would be very thankful for any replies explaining it!!!
EDIT : The typo of 'bits' has been changed to 'bytes'. I ask Sorry to the person who made the first edit. I rollbacked the EDIT since I did not notice the change U made. Thanks to all those who made it a point that It must be changed especially @Mike Burton for downvoting the question and to @jalf who seemed to jump to conclusions over my understanding of concepts!!
If the system is 32-bit, size of void pointer is 4 bytes. If the system is 64-bit, size of void pointer is 8 bytes.
In 32-bit operating systems, the int type is usually 32 bits, or 4 bytes.
sizeof(char)
is always 1. Always. The 'block size' you're talking about is just the native word size of the machine - usually the size that will result in most efficient operation. Your computer can still address each byte individually - that's what the sizeof
operator is telling you about. When you do sizeof(int)
, it returns 4 to tell you that an int
is 4 bytes on your machine. Likewise, your structure is 8 bytes long. There is no information from sizeof
about how many bits there are in a byte.
The reason your structure is 8 bytes long rather than 5 (as you might expect), is that the compiler is adding padding to the structure in order to keep everything nicely aligned to that native word length, again for greater efficiency. Most compilers give you the option to pack a structure, either with a #pragma
directive or some other compiler extension, in which case you can force your structure to take minimum size, regardless of your machine's word length.
char
is size 1, since that's the smallest access size your computer can handle - for most machines an 8-bit value. The sizeof
operator gives you the size of all other quantities in units of how many char
objects would be the same size as whatever you asked about. The padding (see link below) is added by the compiler to your data structure for performance reasons, so it is larger in practice than you might think from just looking at the structure definition.
There is a wikipedia article called Data structure alignment which has a good explanation and examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With