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.

Pankaj said:   1 decade ago
In some compiler eg: AVR studio, there is option to disable the padding bytes for structure.

Leenaja said:   1 decade ago
Yes Tapas you are right.

If we consider array variable to struct.

Struct ex e[3], then totally it occupies 21 bytes. So structure can occupy other than 7 bytes also.

Tapas said:   1 decade ago
When we declare a structure no memory is allocated but when we create a data type of that structure i.e. now if we write struct ex e; then 7 byte will be reserved.

Dinesh kumar said:   1 decade ago
The answer is YES.. because they didn't mention any compiler specifications. size of struct should be 1+2+4 = 7.

M.Aparna Shri said:   1 decade ago
I also hope the given answer is correct.Because structure allocates memory in same location with required number of bytes.I too agree that the answer is Yes not No.

Vikas dubey said:   1 decade ago
I dont know this contradiction, But I know that stucture occupies memory depending on the size of members of the class, where as union occupies largest member size...7 is correct one....internal memory occupation is compiler dependent.

Sundar said:   1 decade ago
@Rajendra Singh

The size of the struct is the amount of memory the compiler chooses to devote to it. Different compilers make different choices, because they are concerned with different constraints -- more generally, with different "figures of merit".

The implementation is free to do what it wants, but usually it occupies additional memory based on the alignment requirements of the machine.

I hope the given answer is correct.

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.