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 2 of 2.

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.

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

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

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.

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

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.

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

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;.


Post your comments here:

Your comments will be displayed after verification.