C has no String type. A string is a contiguous sequence of char ending with a '\0' (NUL) byte. The terminator is part of the model, not optional decoration.
char s[] = "hi"; /* {'h','i','\\0'} — length 2, size 3 */
const char *p = "hi"; /* pointer to a string literal */
Mental model: strlen walks until '\0'. If the terminator is missing, it walks off the array — undefined. Every buffer you treat as a string must have room for that extra byte.
Array char s[] = "hi" | Pointer const char *p = "hi" | |
|---|---|---|
| Storage | Mutable copy (if not const) | Points at a literal — do not write |
sizeof | 3 | size of a pointer |
| Reseat | Cannot s = … | Can point elsewhere |
char buf[8] = "hi"; buf[0] = 'H'; /* ok */ /* Incorrect */ char *q = "hi"; q[0] = 'H'; /* undefined — literal */
Include <string.h>. Lengths are size_t.
| Function | Does | Trap |
|---|---|---|
strlen(s) | Count before NUL | No NUL → UB. Does not include the NUL in the count. |
strcpy(dst, src) | Copy including NUL | No bounds. Prefer snprintf or C11 strcpy_s (optional Annex K — often missing). Use a length-aware copy. |
strncpy | Copy up to n | May omit the NUL if src is long. Not “safe strcpy.” |
strcmp | Lexicographic order | 0 means equal. Not a boolean. |
strcat | Append | Needs room in dst for both + NUL. |
strchr / strstr | Find | NULL if missing. |
memcpy / memmove | Raw bytes | memmove if overlap. Not string-aware. |
char dst[8]; snprintf(dst, sizeof dst, "%s", src); /* always NUL-terminates if size > 0 */
fgets(buf, sizeof buf, stdin) reads at most size−1 characters and stores a NUL. It may keep the newline.gets — removed from C11. It cannot be used safely.char line[128];
if (fgets(line, sizeof line, stdin) == NULL) {
/* EOF or error */
}
if (strcmp(a, b) == 0) { /* equal */ }
if (strncmp(a, b, n) == 0) { /* first n chars */ }
if (strcmp(a, b)) when you mean equal — nonzero means unequal.strcmp < 0, 0, > 0 like memcmp.strcpy into a buffer sized for strlen without +1.char *.strncpy as a security fix — still may lack a terminator.sizeof on a char * parameter thinking it is the buffer length.snprintf / memcpy + explicit NUL over strcpy/strcat.const char *. Mutable text lives in an array you own.strcmp == 0 for equality. Length is strlen, size is strlen+1.~ Good luck with your revision! ~