🇯🇵 日本語 | 🇺🇸 English
Advertisement

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 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 shows up constantly — commit it to memory.

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.
Comparing with == directly would compare addresses, not contents, so always use strcmp for string comparison in C.

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 a string 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 different.

Result

Please answer the questions
Home