6. Arrays & StringsBeginner9 min read
Strings & String Manipulation in C
Master null-terminated character arrays, safe string input with fgets(), and essential string.h functions (strlen, strcpy, strcat, strcmp).
Key Takeaways & Core Concepts
- In C, strings are 1D character arrays terminated by a special null character
\0(ASCII 0). - An array holding a 6-character word requires at least 7 bytes of storage for the null terminator.
- Never use
gets()because it causes fatal buffer overflows; always usefgets()with buffer limits. <string.h>provides standard functions:strlen(),strcpy(),strcat(), andstrcmp().
How Strings Work Under the Hood
Unlike languages with a native string object, C treats strings as raw character arrays:
C Code Example
1char site[] = "CodeZov";
2// In memory: ['C', 'o', 'd', 'e', 'Z', 'o', 'v', '\0']
3// Total bytes allocated: 7 letters + 1 null terminator = 8 bytes
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
3 lines
The null character \0 marks where the string ends in memory. Library functions scan characters sequentially until they reach \0.
Standard String Functions (<string.h>)
Standard string utility functions:
strlen(s): Returns number of characters excluding the null terminator.strcpy(dest, src): Copiessrcintodest(including\0).strcat(dest, src): Appendssrcto the end ofdest.strcmp(s1, s2): Compares two strings lexicographically (returns0if identical).
Comprehensive String Manipulation
1#include <stdio.h>
2#include <string.h>
3
4int main(void) {
5 char first[30] = "CodeZov";
6 char second[] = " Platform";
7 char clone[30];
8
9 // 1. Length
10 printf("Length of first: %zu\n", strlen(first));
11
12 // 2. Copying
13 strcpy(clone, first);
14 printf("Cloned string: %s\n", clone);
15
16 // 3. Concatenation
17 strcat(first, second);
18 printf("After concatenation: %s\n", first);
19
20 // 4. Comparison
21 if (strcmp(clone, "CodeZov") == 0) {
22 printf("Strings match exactly!\n");
23 }
24
25 return 0;
26}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
26 lines
Note: strcmp returns 0 when strings have identical characters up to their null terminators.
Practice & AssessmentC Programming Complete Course
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 1 correct(0 attempted)
1
What is the minimum array size needed to store the word 'HELLO' as a C string?
Beginner