How to work with C strings
Understand termination
A C string is a character sequence ending in '\0'. The destination needs one extra byte for that terminator.
char word[] = "hello";
printf("%zu\n", sizeof word); // 6 bytes
Use string functions
Include string.h. Use strlen only on a valid terminated string and strcmp rather than == to compare text.
if (strcmp(command, "quit") == 0) {
printf("Goodbye\n");
}
Read a bounded line
fgets limits the write to the array size. Remove a trailing newline only if one was actually read.
char name[64];
if (fgets(name, sizeof name, stdin) != NULL) {
name[strcspn(name, "\n")] = '\0';
}
Copy with a known capacity
Avoid strcpy and unbounded concatenation when input length is not proven. snprintf terminates when capacity is nonzero and reports the length it wanted to write.
char label[32];
int needed = snprintf(label, sizeof label, "User: %s", name);
if (needed < 0 || (size_t) needed >= sizeof label) {
fprintf(stderr, "Label was too long.\n");
}