Strings in C & string.h Library
Unlike modern languages, C does not have a native string data type. Strings in C are simply arrays of characters terminated by a null character `\0`.
What is it?
A C string is an array of `char` terminated by the null byte `\0` (ASCII 0). The `<string.h>` library provides functions to manipulate them.
Why is it used?
Text processing, reading user commands, parsing filenames, and network string handling.
Detailed Explanation
The Null Terminator (`\0`):
Every C string must reserve one extra byte for the terminating null character `\0`. For example, `"IGM"` requires 4 bytes: `'I'`, `'G'`, `'M'`, and `'\0'`.
Key `<string.h>` Functions:
• `strlen(s)`: Returns length of string (excluding `\0`).
• `strcpy(dest, src)`: Copies `src` to `dest`.
• `strcat(dest, src)`: Concatenates `src` to the end of `dest`.
• `strcmp(s1, s2)`: Compares strings (returns 0 if identical!).
Syntax Structure
Syntax Blueprint
#include <string.h>
char name[20] = "Python";
int len = strlen(name);
Code Example
C Code
#include <stdio.h>
#include <string.h>
int main() {
// String declaration and initialization
char course[30] = "Advanced Python";
char institute[] = "IGM Computer Institute";
printf("Course Name: %s\n", course);
printf("Course Length: %zu characters\n", strlen(course));
// String Comparison (strcmp returns 0 if exact match)
if (strcmp(course, "Advanced Python") == 0) {
printf("Match Confirmed: Course is Advanced Python.\n");
}
// Safe Concatenation
char full_title[60] = "KLiC ";
strcat(full_title, course);
printf("Full Title: %s\n", full_title);
return 0;
}
Explanation of the Code
• `strlen(course)` counts characters up to the null terminator.
• `strcmp(s1, s2) == 0` tests for string equality (do not use `s1 == s2`—that compares pointer addresses!).
• `strcat` joins strings together into the destination buffer.
Expected Output
Course Name: Advanced Python
Course Length: 15 characters
Match Confirmed: Course is Advanced Python.
Full Title: KLiC Advanced Python
Real-World Application
Used across operating system system calls, URL routing in C web servers (Nginx), and database drivers.
Common Mistakes to Avoid
• Comparing strings with `s1 == s2` (this checks if they have the same memory address, not if text matches!). Always use `strcmp()`.
• Buffer overflow when using `strcpy` or `strcat` into an array that is too small.
Quick Practice Challenge
Declare a string `'Hello'` and verify that `sizeof("Hello")` is 6 bytes (including `\0`).
Key Takeaways
• C strings are null-terminated character arrays (`\0`).
• Always use `strcmp()` to compare string contents.
• Allocate at least `length + 1` bytes to hold the null terminator.