C
Adding questions
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.
Exercise 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);.
Show example 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;
}
Test yourself
-
Match add_question parts
- struct Question *q
- Question array
- int *count
- Count pointer
- const char *text
- Question text
- int correct
- Correct answer
-
Why use *count in add_question?
- To modify the counter
- To allocate memory
- To copy strings
- For a loop
Show answer
To modify the counter — *count lets the function modify the caller's counter.
-
Count increment expression
(*____)++;
Show answer
(*count)++;
Next lesson: Running the quiz