Introduction & Syntax
Strings · Study material
A string in C is an array of char that ends with the null character '\0'. C has no string type: every function in <string.h> simply walks memory until it meets that zero byte. That makes strings fast and flexible, and it is also why buffer overflows, missing terminators and string-literal crashes are among the most common C bugs. This page teaches strings the modern, safe way, then gives you 40 practice questions checked on a real compiler.
On this page
- String literals vs char arrays,
strlenvssizeof - Reading input safely with
fgets() - The
<string.h>functions you will use every day snprintf(),strtok(), UTF-8 and what C23 adds
What is a string in C?
char word[] = "Frenzy"; creates an array of 7 bytes: the 6 letters plus a terminating '\0' that the compiler adds. strlen() counts the characters before the terminator; sizeof measures the whole array.
char word[] = "Frenzy";
- F0
- r1
- e2
- n3
- z4
- y5
- \06
#include <stdio.h>
#include <string.h>
int main(void) {
char word[] = "Frenzy"; /* 6 letters + '\0' = 7 bytes */
printf("strlen = %zu, sizeof = %zu\n", strlen(word), sizeof word);
word[0] = 'f'; /* an array is writable */
printf("%s, code of word[6] = %d\n", word, word[6]);
return 0;
}
strlen = 6, sizeof = 7 frenzy, code of word[6] = 0
String literal vs char array
| Declaration | What you get | Can you change it? |
|---|---|---|
char a[] = "hi"; | your own 3-byte array, a copy of the literal | Yes |
const char *p = "hi"; | a pointer to the literal, often in read-only memory | No – changing it is undefined behaviour |
char a[8] = "hi"; | 8 bytes: h, i, then six '\0' | Yes |
char a[2] = "hi"; | legal in C, but no room for '\0' – not a string | Yes, but never pass it to string functions |
Declare pointers to literals as const char *; the compiler then stops you from writing through them.
Reading strings safely
gets() was removed from C in C11 because it cannot know the buffer size. scanf("%s", s) stops at the first space and also has no limit unless you write one (%15s). The safe, standard way to read a line is fgets(), which keeps the newline – remove it with strcspn().
#include <stdio.h>
#include <string.h>
int main(void) {
char name[16];
if (fgets(name, sizeof name, stdin) == NULL) /* never reads more than 15 chars */
return 1;
name[strcspn(name, "\n")] = '\0'; /* drop the newline fgets keeps */
printf("Hello, %s! (%zu characters)\n", name, strlen(name));
return 0;
}
Asha Rao
Hello, Asha Rao! (8 characters)
Everyday string.h functions
| Function | Does | Watch out |
|---|---|---|
strlen(s) | length before '\0' (size_t) | O(n): do not call it in every loop test |
strcpy(d, s) / strcat(d, s) | copy / append | no size check – d must be big enough |
strncpy(d, s, n) | copy at most n chars | no '\0' when s has n or more chars |
strcmp(a, b) | < 0, 0 or > 0 | not necessarily −1 or 1; never compare strings with == |
strchr(s, c) / strstr(s, t) | find a char / a substring | return NULL when not found |
strcspn(s, set) | length of the prefix with no char from set | perfect for trimming '\n' |
#include <stdio.h>
#include <string.h>
int main(void) {
char a[20] = "learn";
strcat(a, "frenzy"); /* a has room for 19 chars + '\0' */
printf("%s %zu\n", a, strlen(a));
printf("%d %d %d\n", strcmp("apple", "banana") < 0,
strcmp("abc", "abc") == 0, strcmp("b", "a") > 0);
char *f = strchr(a, 'f'); /* first 'f', or NULL */
printf("%s (at index %td)\n", f, f - a);
return 0;
}
learnfrenzy 11 1 1 1 frenzy (at index 5)
Building strings with snprintf()
snprintf(buf, size, ...) never writes more than size bytes and always ends the result with '\0'. Its return value is the length the full result would have had, so you can detect truncation.
#include <stdio.h>
int main(void) {
char buf[12];
const char *kinds[] = {"ORDER", "INVOICE"};
int ids[] = {42, 12345};
for (int i = 0; i < 2; i++) {
int need = snprintf(buf, sizeof buf, "%s-%04d", kinds[i], ids[i]);
printf("%-12s needed %2d chars, truncated: %s\n", buf, need,
need >= (int) sizeof buf ? "yes" : "no");
}
return 0;
}
ORDER-0042 needed 10 chars, truncated: no INVOICE-123 needed 13 chars, truncated: yes
Splitting with strtok()
strtok() writes '\0' into your string and remembers its position between calls, so the string must be writable, and two splits cannot run at the same time. Empty fields are skipped.
#include <stdio.h>
#include <string.h>
int main(void) {
char line[] = "C,Java,,Python"; /* must be writable: strtok changes it */
for (char *t = strtok(line, ","); t != NULL; t = strtok(NULL, ","))
printf("[%s]\n", t);
return 0;
}
[C] [Java] [Python]
Characters, UTF-8 and C23
The <ctype.h> functions (isalpha, toupper …) expect a value that fits in unsigned char; pass (unsigned char) c, because a plain char can be negative. In UTF-8 text a letter such as é takes 2 bytes, so strlen() counts bytes, not characters. C23 makes strdup() and strndup() part of standard C and adds memccpy() for fast bounded copying.
Common string mistakes
- No room for '\0': "Hello" needs 6 bytes, not 5.
- Comparing with ==: it compares addresses; use
strcmp(). - Writing to a literal:
char *s = "hi"; s[0] = 'H';may crash. - Overflowing with strcpy/strcat: check sizes or use
snprintf(). - Forgetting the terminator after building a string by hand.
Key points to remember
- A C string is a char array that ends with '\0'; size = length + 1.
strlencounts characters,sizeofcounts bytes of the array.- Read lines with
fgets(), build text withsnprintf(), parse numbers withstrtol(). - String literals are read-only: point to them with
const char *. - Cast to
unsigned charbefore calling ctype functions.
Frequently asked questions
Why does C need '\0' at the end of a string?
Because a C string carries no length. Every function finds the end by looking for the zero byte.
What is the difference between strlen() and sizeof?
strlen() runs at run time and counts characters before '\0'. sizeof is the size of the array (or of the pointer, if you only have a pointer).
Is strcpy() unsafe?
It is safe only when you know the destination is large enough. When the length is not under your control, use snprintf() or check strlen() first.
Where can I learn strings step by step?
Read Strings in C, String Functions in C and String Programs for Practice, then practise with the exercises below.