In C programming, structures (often referred to as “structs”) provide a way to group together variables of different data types under a single name. These variables can be of primitive data types such as int, float, or char, and they can also be arrays or other structures. If you’re a novice C programmer or brushing up on foundational concepts, this quiz on structures will test your understanding!
Each question is followed by the correct answer and an explanation to help reinforce your knowledge.
1. Which keyword is used to define a structure?
Answer:
Explanation:
In C, the struct keyword is used to define a structure.
2. Consider the following code:
struct student {
int id;
char name[20];
};
Answer:
Explanation:
‘student’ is a structure type. We can use this type to declare variables of this structure.
3. How do you access the ‘id’ of a structure variable ‘stu’ of type ‘student’?
Answer:
Explanation:
The dot operator . is used to access the members of a structure variable.
4. What will be the size of the structure student in memory (assuming an int takes 4 bytes and a char takes 1 byte)?
Answer:
Explanation:
The size would be the sum of the size of an int (4 bytes) and the size of the character array (20 bytes) = 24 bytes.
5. What does the following code do?
typedef struct student {
int id;
char name[20];
} Student;
Answer:
Explanation:
The typedef keyword is used to create an alias. Here, ‘Student’ becomes an alias for ‘struct student’.
6. How can you define a structure variable at the time of structure declaration?
Answer:
Explanation:
This code snippet defines a structure of type ‘student’ and also declares a variable ‘stu’ of that type.
7. If ‘ptr’ is a pointer to a structure variable, how do you access the members of the structure?
Answer:
Explanation:
When you have a pointer to a structure, the ‘->’ operator is used to access its members.
8. Can a structure in C contain a member of its own type?
Answer:
Explanation:
A structure cannot contain a member of its own type directly because the size of the structure would become indeterminate. However, it can contain a pointer to its own type.
9. Which of the following initializes a structure variable stu with id as 100 and name as “John”?
Answer:
Explanation:
This is the correct way to initialize a structure variable with given values.
10. Structures in C can contain:
Answer:
Explanation:
In C, structures can contain only data members. Member functions are a feature of classes in C++.