What is the size of the following structure in C++: struct Employee { int id; char name[20]; float salary; };
A. 28 bytes
B. 20 bytes
C. 8 bytes
D. 32 bytes
Answer: Option D
Solution(By Examveda Team)
In C++, the size of a structure is determined by the sum of the sizes of its individual members, taking into account padding for alignment. TheEmployee
structure consists of three members: an integer id
, an array of characters name
of size 20, and a float salary
.The size of an integer is typically 4 bytes, the size of a float is also typically 4 bytes, and the size of each character in the array depends on the character set being used (usually 1 byte per character). However, due to memory alignment requirements, additional padding may be added after the
name
array to ensure proper alignment of subsequent members.So, the calculation of the structure size would be:
int id
: 4 byteschar name[20]
: 20 bytesPadding to align
salary
to the next 4-byte boundary (assuming 4-byte alignment)float salary
: 4 bytesTotal: 4 bytes (id) + 20 bytes (name) + 4 bytes (padding) + 4 bytes (salary) = 32 bytes.
Therefore, the correct answer is Option D: 32 bytes.
To calculate the size of a structure in C++, you sum up the sizes of its individual members, taking into account any padding added by the compiler for alignment.
In the given structure Employee:
int id; typically occupies 4 bytes on most systems.
char name[20]; is an array of 20 characters. Each character typically occupies 1 byte. So, the total size of this array would be 20 bytes.
float salary; typically occupies 4 bytes on most systems.
Considering padding for alignment, the total size of the structure would be the sum of the sizes of its members:
Size of structure
=
Size of int
+
Size of char array
+
Size of float
Size of structure=Size of int+Size of char array+Size of float
Size of structure
=
4
+
20
+
4
=
28
bytes
Size of structure=4+20+4=28 bytes
Therefore, the correct answer is:
A. 28 bytes