C Programming - Structures, Unions, Enums - Discussion

Discussion Forum : Structures, Unions, Enums - Yes / No Questions (Q.No. 12)
12.
If a char is 1 byte wide, an integer is 2 bytes wide and a long integer is 4 bytes wide then will the following structure always occupy 7 bytes?
struct ex
{
    char ch;
    int i;
    long int a;
};
Yes
No
Answer: Option
Explanation:
A compiler may leave holes in structures by padding the first char in the structure with another byte just to ensures that the integer that follows is stored at an location. Also, there might be 2extra bytes after the integer to ensure that the long integer is stored at an address, which is multiple of 4. Such alignment is done by machines to improve the efficiency of accessing values.
Discussion:
18 comments Page 1 of 2.

Venkatesh said:   1 decade ago
answer is 8 Bytes. Because here structure padding is coming to picture.

1. Byte memory will allocate first.
2. Bytes allocate for int but after char int will stars from multiple of 2 memory location till now structure size is (1char+1 int padding+2 int)=4 bytes.

Now 4 bytes will allocate for long here no structure padding is required because here memory will starts from multiples of 4 already, So instantly 4 bytes memory for long will allocate for long.

So total size is:(1char+1 for int padding+2 int+4 for long) = 8 bytes.

MAHESH said:   5 years ago
Yes, I agree @Venkatesh.

#include<stdio.h>
struct ex
{
char ch;
int i;
long int a;
};

void main()
{
struct ex x;
printf("%d",sizeof(x));
}
answer is:16 for 64 bit,8 for 32 bit;

It allocates memory like char 2 bytes(1 for char + 1 for padding(holes)), and 2 for int and long int takes 4 bytes so, total it takes 8 bytes answer is NO;.

J.Mounika said:   7 years ago
Can anyone tell me the correct answer with the explanation?

Srinivas bandreddy said:   8 years ago
#include<stdio.h>
struct ex
{
char ch;
int i;
long int a;
};

void main()
{
struct ex x;
printf("%d",sizeof(x));
}
This output is 7 ,So answer is A.

Srinivas said:   8 years ago
Answer is 7 in turbo C.

Amit Saxena said:   9 years ago
I agree to the answer "yes".

The contradiction mentioned above didn't work with the most compiler. So the answer should be yes.

Arj said:   1 decade ago
Adding of extra byte as wholes in structure called structure padding.

Bharath said:   1 decade ago
Can any one explain what is structure padding?

Rahul said:   1 decade ago
I hope that the given option is wrong because structure can store different that types and it should be 1+2+4 = 7.

Rajendra Singh said:   1 decade ago
There was a problem with answer of question number 11. It's output result should be 7. So the answer will option "A" means TRUE. It was tested on TURBO C++ compiler...


Post your comments here:

Your comments will be displayed after verification.