Interview Questions on C - Structures & Unions
1. Explain about Structures?
Structure is collection of different datatypes of elements.
2. How to create instance for the structure?
Syn :- struct structure_name instance_name;
Ex :- struct Books Book1;
3. When is the memory will be allocated for structure?
When we create instance for that structure. Memory will no be allocated until you create the instance member for the structure.
struct Books book1;
Here when we create book1, the memory will be allocated.
4. How to access structuremembers?
By using instance name;
5. Explain about Union?
Union is collection of different datatypes of elements.
6. What is the difference between structure and union?
1.The keyword struct is used to define a structure 1. The keyword union is used to define a union.
2. When a variable is associated with a structure, the compiler allocates the memory for each member. The size of structure is greater than or equal to the sum of sizes of its members. The smaller members may end with unused slack bytes. 2. When a variable is associated with a union, the compiler allocates the memory by considering the size of the largest memory. So, size of union is equal to the size of largest member.
3. The address of each member will be in ascending order This indicates that memory for each member will start at different offset values. 3. The address is same for all the members of a union. Thisindicates that every member begins at the same offset value.
4. Individual member can be accessed at a time 4. Only one member can be accessed at a time.
5. Several members of a structure can initialize at once. 5. Only the first member of a union can be initialized.
7. Explain about typedef ?
Typedef is used to create own user defined data types.
Syn :- typdef primarydatatype userdefineddatatype;
1. typdef int num;
2. Typedef struct books BOOK;
8. typedef vs #define?
1. The typedef is limited to giving names to types only.
#define can be used to define alias for values as well
2. The typedef interpretation is performed by the compiler.
#definestatements are processed by the pre-processor.