Lesson content
Read, practise, then check your understanding
C has no built-in string type. A string is an array of char ending with a null byte ('\0'). The capacity of an array and its current string length are different values.
char editable[16] = "hello"; // capacity 16, length 5
const char *literal = "world"; // do not modify a string literal
Length, copy, and comparison
<string.h> declares strlen, strcmp, memcpy, memmove, memset, and related functions. strlen scans to a null terminator and excludes it.
if (strcmp(command, "start") == 0) {
start_service();
}
Do not compare text with ==; that compares pointer values.
Bounded construction
Before copying, prove that destination capacity is at least source length + 1.
int copy_text(char *destination, size_t capacity, const char *source) {
if (!destination || !source) return 0;
size_t length = strlen(source);
if (length >= capacity) return 0;
memcpy(destination, source, length + 1);
return 1;
}
strncpy is not a universal safe replacement: it may omit termination and pads unused capacity. Prefer an interface whose truncation or failure policy is explicit. snprintf is useful for formatted text and returns the length that would have been written.
Reading input
Never use gets. Use fgets, check its result, and remove a trailing newline if present.
char line[128];
if (fgets(line, sizeof line, stdin) != NULL) {
line[strcspn(line, "\n")] = '\0';
}
If input exceeds capacity, fgets reads only part. Robust code detects a missing newline and drains or grows the buffer according to policy.
Bytes, Unicode, and parsing
A C string is a byte string. UTF-8 can represent one character with multiple bytes, so strlen counts bytes, not user-perceived characters. For numbers, prefer strtol or strtod over atoi; they expose errors and the unparsed suffix. Always carry capacity with writable buffers and treat external text as untrusted.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.