Interview Questions
Strings · Study material
C Strings Interview Questions and Answers
1. How is a string stored in C?
As a char array ending with the null character '\0'. There is no length field, so functions find the end by scanning for the zero byte.
2. What is the difference between char s[] = "hi" and char *s = "hi"?
The first creates a writable 3-byte array initialised from the literal. The second points to the literal itself, which may be in read-only memory; modifying it is undefined behaviour, so write const char *s.
3. Why was gets() removed?
It cannot know the size of the buffer, so any long input overflows it. It was deprecated in C99 and removed in C11; use fgets().
4. What does strcmp() return?
A negative value, zero or a positive value depending on the first differing character (compared as unsigned char). The exact value is not specified.
5. Why is strncpy() considered tricky?
If the source has n or more characters, it does not write a terminator, and if it is shorter it pads the rest with zeros. You usually need d[n - 1] = '\0'.
6. What does snprintf() return?
The number of characters the complete output would need (without '\0'), or a negative value on error. A value ≥ the buffer size means the result was truncated.
7. Why should you not use == to compare strings?
It compares two addresses, not the characters. Two equal strings at different addresses compare unequal.
8. Is strtok() thread-safe?
No. It keeps hidden state between calls. Use strtok_r() (POSIX) or strtok_s() where available, or parse with strcspn()/strspn().
9. Why cast to unsigned char before toupper()?
The ctype functions accept an int that is EOF or representable as unsigned char. A plain char can be negative for bytes above 127, which is undefined behaviour.
10. What does strlen() return for a UTF-8 string like "héllo"?
6 – it counts bytes, and é takes 2 bytes in UTF-8.
11. What is the difference between atoi() and strtol()?
atoi() has no error reporting (and overflow is undefined). strtol() returns where parsing stopped and sets errno to ERANGE on overflow.
12. What changed for strings in C23?
strdup() and strndup() became standard, memccpy() was added, and u8"" literals now have type char8_t arrays (an unsigned char type).