Interview Questions on C - Structures & Unions
1. Explain about Structures?
Structure is collection of different datatypes of elements.
Syn :-
Struct structurename{
Datatype identifier1;
Datatype identifier2;
Datatype identifier1;
};
Ex :-
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} ;
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.
Ex:-
struct Books
{
char title[50];
char author[50];
};
struct Books book1;
Here when we create book1, the memory will be allocated.
4. How to access structuremembers?
By using instance name;
Ex:- book1.title;
book1.author;
5. Explain about Union?
Union is collection of different datatypes of elements.
Syn :-
Union union_name{
Datatype identifier1;
Datatype identifier2;
Datatype identifier1;
};
Ex:-
union Data
{
int i;
float f;
char str[20];
};
6. What is the difference between structure and union?
Structure 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;
Ex:-
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.