Adding questions
- C course
- Intermediate
- Lesson 43/116
- 6 min
Learn to add questions with the AddQuestion function.
Adding questions
The second lesson defines the add_question function. This function adds a question to the array and increments the counter. Pointer use is required so the counter can be modified.
Signature: void add_question(struct Question *q, int *count, const char *text, int correct). Body: strcpy(q[*count].text, text); q[*count].correct = correct; (*count)++;. Here count is a pointer; the function must change the caller's value. strcpy safely copies the string. The previous lesson's solution is in the starting code.
strcpy and count increment
The body of add_question does two core operations: string copy and count increment. Both rely on pointer logic.
The call strcpy(q[*count].text, text); copies text into the *count'th element of the array. (*count)++ then increments the counter. Parentheses are required; writing *count++ parses as *(count++) and updates the wrong element. Pointer arithmetic requires care with such distinctions. This pattern is the foundation of dynamic array management in C.
Practice Write the add_question function
Write void add_question(struct Question *q, int *count, const char *text, int correct). In the body copy the text with strcpy(q[*count].text, text);, assign q[*count].correct = correct;, increment with (*count)++;. In main, declare struct Question questions[10]; int count = 0;; call add_question(questions, &count, "Başkent?", 0); and add_question(questions, &count, "2+2?", 1);; print with printf("%d soru eklendi\n", count);.
Starter code
#include <stdio.h>
#include <string.h>
struct Question {
char text[64];
int correct;
};
// Write the add_question function (q, count, text, correct)
// In main add 2 questions and print how many were added
int main(void) {
printf("Quiz hazır\n");
return 0;
}Sample solution
#include <stdio.h>
#include <string.h>
struct Question {
char text[64];
int correct;
};
void add_question(struct Question *q, int *count, const char *text, int correct) {
strcpy(q[*count].text, text);
q[*count].correct = correct;
(*count)++;
}
int main(void) {
struct Question questions[10];
int count = 0;
add_question(questions, &count, "Başkent?", 0);
add_question(questions, &count, "2+2?", 1);
printf("%d soru eklendi\n", count);
return 0;
}Expected output
2 soru eklendi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match add_question parts
| Term | Meaning |
|---|---|
struct Question *q |
Question array |
int *count |
Count pointer |
const char *text |
Question text |
int correct |
Correct answer |
2 Why use *count in add_question?
- To modify the counter Correct answer
- To allocate memory
- To copy strings
- For a loop
Explanation: *count lets the function modify the caller's counter.
3 Count increment expression
(*____)++;
(*count)++;
Explanation: (*count)++ increments the counter through the pointer.