🇯🇵 日本語 | 🇺🇸 English

Lesson 23: Quiz (Strings)

Test your understanding of null termination, strlen vs sizeof, strcmp, and string assignment.

Question 1 — End of a string

char s[] = "Hello";
printf("%lu\n", sizeof(s));

What does this print?

5
6
4
Compile error
Explanation: String literals automatically have a '\0' (null terminator) appended.
"Hello" is H, e, l, l, o, \0 — 6 bytes in total.

Question 2 — strlen vs sizeof

char s[] = "ABC";
printf("strlen=%lu, sizeof=%lu\n", strlen(s), sizeof(s));

What does this print?

strlen=3, sizeof=3
strlen=3, sizeof=4
strlen=4, sizeof=4
strlen=4, sizeof=3
Explanation: strlen returns the number of characters excluding '\0' → 3. sizeof returns the size in bytes including '\0' → 4.
This distinction comes up all the time — make sure to remember it.

Question 3 — Return value of strcmp

char a[] = "apple";
char b[] = "apple";
if (strcmp(a, b) == 0) {
    printf("same\n");
} else {
    printf("different\n");
}

What does this print?

same
different
Compile error
Undefined behavior
Explanation: strcmp returns 0 when the two strings are equal.
Using == directly would compare addresses instead of contents, so in C you should always use strcmp to compare strings.

Question 4 — Assigning a string

char s[10];
s = "Hello";
printf("%s\n", s);

What happens?

Hello
Compile error
Empty string
Undefined behavior
Explanation: You can't assign to an array with =. Use strcpy(s, "Hello") instead.
The form char s[] = "Hello" at declaration time is initialization, which is allowed. Initialization and assignment are not the same thing.

Result

Answer all the questions to see your score.
Home