Strings
Strings in C: char arrays with null terminator, literals, input/output, standard library functions, memory layout, and safe handling.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Strings represent text: sensor labels, file paths, user input, configuration, and protocol messages. Engineers often need to parse logs, validate inputs, and build formatted messages; understanding how C stores and manipulates strings is essential to write correct and safe programs.
Key ideas
- String: A string in C is defined as "a finite sequence of characters terminated by the null character
\0and stored in contiguous memory." Assumptions: characters are stored in bytes, and the sentinel\0marks the end. Consequence: the length of a C string is the count of bytes before the first\0. - Null terminator (
\0): A special character with integer value 0 that ends the string. Without it, functions likeprintf("%s")andstrlenwill read past the intended end, causing undefined behavior. - String literal: A sequence of characters in double quotes, e.g.,
"Hello". It has static storage duration. Modifying a string literal results in undefined behavior; many implementations place literals in read-only memory. Useconst char *p = "Hello";to reflect that it should not be modified. - Character array vs. pointer to literal:
char a[] = "Hi";creates a modifiable array:{'H','i','\0'}. You may changea[0] = 'h';.char *p = "Hi";points to a read-only literal; writingp[0] = 'h';is undefined behavior.
- String length vs. array size:
- Length: Number of characters before
\0, given bystrlen(s). Does not count\0. - Size: Total storage allocated for the array, given by
sizeof swhensis an array in scope. Forchar s[10] = "abc";,strlen(s) == 3,sizeof s == 10.
- Length: Number of characters before
- Initialization:
- With literal:
char s[] = "Hello"; // size 6 including '\0' - With characters:
char t[6] = {'H','e','l','l','o','\0'}; - Uninitialized arrays contain indeterminate values; always set or zero-initialize before use.
- With literal:
- Indexing and iteration: Strings are arrays of
charwith indices from 0 up tolength-1. Always stop at\0. - Input and output:
printf("%s", s)prints characters until\0.scanf("%s", s)reads up to first whitespace; risky unless you limit width to avoid overflow.fgets(s, n, stdin)reads up ton-1chars or newline, stores\0, and keeps the newline if read. It is safer for lines with spaces.getswas removed from the C standard due to insecurity; never use it.puts(s)writessthen a newline.
- Escape sequences: Special backslash forms inside character and string literals. Common ones:
\nnewline,\ttab,\\backslash,\"double quote,\0null character. - String library (
string.h) — partial list:strlen(s): length excluding\0.strcpy(dst, src): copiessrcincluding\0todst; requiresdstlarge enough.strncpy(dst, src, n): copies up tonchars; does not guarantee\0ifsrclength ≥n.strcat(dst, src): appendssrcto end ofdst;dstmust have space.strncat(dst, src, n): appends up tonchars; writes\0.strcmp(a, b): lexicographic compare; returns <0, 0, >0.strncmp(a, b, n): compares at mostnchars.strchr(s, c): pointer to first occurrence ofcinsorNULL.strstr(h, n): pointer to first occurrence of substringninhorNULL.strtok(s, delim): tokenizessusing delimiters; modifies input and is not thread-safe. On POSIX usestrtok_r, and in C11 Annex K (if available) usestrtok_s, for reentrant/thread-safe tokenization.
- Character classification and case conversion (
ctype.h):isalpha,isdigit,isspace,tolower,toupper. Rule: when passing acharto these macros, first cast tounsigned char(or useEOF) to avoid undefined behavior for negativecharvalues. - Memory safety with strings:
- Buffers must be large enough for content plus
\0. - Prefer input limits:
scanf("%49s", s),fgets(s, sizeof s, stdin). - Beware off-by-one errors when copying/appending.
strncpytruncation pitfalls: if truncation occurs, you may need to manually add\0.snprintfsafely formats into a buffer with size limit and always null-terminates (if size > 0).
- Buffers must be large enough for content plus
- Memory layout (diagram to draw in exam):
- Draw a box row for
char name[6] = "Hello";. Label indices 0..5. Write cells: index 0 'H', 1 'e', 2 'l', 3 'l', 4 'o', 5 '\0'. Draw an arrow labeling the base address&name[0]. Optionally, annotate thatsizeof name = 6,strlen(name) = 5.
- Draw a box row for
- Definition of undefined behavior (for context): Program behavior for which the C standard imposes no requirements. Examples here: reading a string without
\0, writing into string literals, overrunning buffers.
Formulas
char s[6] = "Hello";char t[] = "abc"; // size becomes 4 including '\0'const char *p = "Read-only literal";- Basic I/O with strings
printf("%s", s);scanf("%49s", s); // reads a word, limits to 49 chars + '\0'fgets(s, sizeof s, stdin); // reads a line incl. spaces, keeps '\n' if roomputs(s); // prints s and a newline
- Common library functions (string.h)
size_t strlen(const char *s);char *strcpy(char *dst, const char *src);char *strncpy(char *dst, const char *src, size_t n);char *strcat(char *dst, const char *src);char *strncat(char *dst, const char *src, size_t n);int strcmp(const char *a, const char *b);int strncmp(const char *a, const char *b, size_t n);char *strchr(const char *s, int c);char *strstr(const char *haystack, const char *needle);char *strtok(char *str, const char *delim);
- Character classification (ctype.h)
int isalpha(int c); int isdigit(int c); int isspace(int c);int tolower(int c); int toupper(int c);- Usage note:
if (isalpha((unsigned char)ch)) { ... }
- Safe formatting
int snprintf(char *dst, size_t size, const char *fmt, ...);
- Escape sequences in literals
"Line1\nLine2","Tab\tSeparated","Quote: \"","Backslash: \\","Null: \0"
Worked examples
Example 1 — Read a full line and count characters, digits, vowels, and words Program:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int main(void) {
char line[256];
if (!fgets(line, sizeof line, stdin)) {
return 0; // no input
}
// Remove trailing newline if present
size_t len = strlen(line);
if (len > 0 && line[len - 1] == '\n') {
line[len - 1] = '\0';
len--; // length excluding newline
}
int vowels = 0, digits = 0, words = 0;
bool in_word = false;
for (size_t i = 0; line[i] != '\0'; i++) {
unsigned char ch = (unsigned char)line[i];
char lower = (char)tolower(ch);
if (lower == 'a' || lower == 'e' || lower == 'i' || lower == 'o' || lower == 'u') {
vowels++;
}
if (isdigit(ch)) {
digits++;
}
if (!isspace(ch)) {
if (!in_word) {
in_word = true;
words++;
}
} else {
in_word = false;
}
}
printf("Characters (excluding newline): %zu\n", len);
printf("Vowels: %d\n", vowels);
printf("Digits: %d\n", digits);
printf("Words: %d\n", words);
return 0;
}
Sample input:
Hello India 2025!
Exact output:
Characters (excluding newline): 17
Vowels: 5
Digits: 4
Words: 3
Example 2 — Reverse a string in place (line with spaces) Program:
#include <stdio.h>
#include <string.h>
void reverse(char *s) {
size_t i = 0, j = strlen(s);
if (j == 0) return;
j--; // last character index
while (i < j) {
char tmp = s[i];
s[i] = s[j];
s[j] = tmp;
i++;
j--;
}
}
int main(void) {
char s[128];
if (!fgets(s, sizeof s, stdin)) return 0;
size_t len = strlen(s);
if (len > 0 && s[len - 1] == '\n') {
s[len - 1] = '\0';
}
printf("Original: %s\n", s);
reverse(s);
printf("Reversed: %s\n", s);
return 0;
}
Sample input:
Programming in C
Exact output:
Original: Programming in C
Reversed: C ni gnimmargorP
Example 3 — Safe concatenation of first and last name with space Program:
#include <stdio.h>
int main(void) {
char first[50], last[50];
char full[101];
// Read first and last names as single words (no spaces inside)
if (scanf("%49s %49s", first, last) != 2) {
return 0;
}
// Safely format into full name buffer
// Ensures null-termination and avoids overflow
int n = snprintf(full, sizeof full, "%s %s", first, last);
if (n < 0 || n >= (int)sizeof full) {
// Truncation occurred or formatting error
// In real programs, handle appropriately
}
printf("Full name: %s\n", full);
return 0;
}
Sample input:
Asha Verma
Exact output:
Full name: Asha Verma
Common mistakes
- Using
getsorscanf("%s", s)without a width limit, causing buffer overflow on long inputs. - Confusing
strlenwithsizeof: writing code that assumessizeof sequals string length whensis not a fixed array (e.g., whensischar *). - Trying to modify string literals via
char *p = "Hi"; p[0] = 'h';— undefined behavior. - Comparing strings with
==instead ofstrcmp;==only compares pointer addresses, not content. - Off-by-one errors in loops and copying, such as copying exactly
nvisible characters but forgetting to leave space for\0. - Misusing
strncpy: assuming it always appends\0. If truncation happens, the destination may not be terminated. - Not handling the trailing newline from
fgets, leading to unexpected extra\nin strings. - Passing a plain
charwith a negative value toisalpha/tolowerwithout casting tounsigned char, causing undefined behavior on some platforms. - Using
strtokon a string literal or using it in multi-threaded contexts without care; it modifies the input and keeps internal state.
For your exam
- Short notes: Differences between
char[]andchar *,strlenvs.sizeof, safe input methods (fgets, width-limitedscanf), and common string functions (strcpy,strcat,strcmp). Include function prototypes and mention headers (string.h,ctype.h). - Programs: Typical tasks include counting characters/digits/words, reversing a string, concatenating names, comparing two strings lexicographically, searching for a substring, or validating that a string is numeric. Use safe I/O, show correct headers, and handle
\nfromfgets. - Diagrams: Memory layout of a string array with indices and
\0. Labelstrlenandsizeofresults. - Best practices to mention: input bounds, always keep space for
\0, avoid modifying string literals, cast tounsigned charforctype.hfunctions, prefersnprintffor formatting. - Marks come from: correct syntax, inclusion of headers, proper termination handling, correct algorithmic logic, and clean, readable output matching the sample format.
Quick check
- Define a C string and explain the role of the null terminator.
- What is the difference between
strlen(s)andsizeof swhensis declared aschar s[20] = "Hi";? - Write the safest single line to read a word (no spaces) of up to 49 characters into
char buf[50];usingscanf.
Answers: 1) A C string is a sequence of char values stored contiguously and terminated by the null character \0; \0 marks the end for all string functions. 2) strlen(s) is 2 (number of visible characters), while sizeof s is 20 (total bytes allocated for the array). 3) scanf("%49s", buf);
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?