C Strings & Characters
Strings: The Hard Way
In most languages, strings are a built-in type with methods and safety nets. In C? A string is just an array of char with a special character β the null terminator '\0' β sitting at the end like a bouncer saying "the string ends here."
There's no .length property. There's no garbage collector managing memory for you. You're on your own, and every string function walks through memory character by character until it hits that '\0'. If the null terminator is missing? The function keeps walking β right off the edge of your data and into whatever garbage is next in memory.
Creating Strings
You have two main approaches:
char greeting[] = "Hello";β the compiler creates a 6-element array (5 letters +'\0')char greeting[6] = {'H','e','l','l','o','\0'};β manual, character by character
Notice the size is 6, not 5. That null terminator needs its own locker.
Creating and Printing Strings
The string.h Toolbox
Since C strings are just arrays, you can't use == to compare them or + to concatenate them. Instead, you use functions from <string.h>:
strlen(s)β returns the length (not counting'\0')strcpy(dest, src)β copiessrcintodeststrcat(dest, src)β appendssrconto the end ofdeststrcmp(a, b)β compares two strings: returns 0 if equal, negative ifa < b, positive ifa > b
Each of these walks character by character until it hits '\0'. That means they're all O(n) β the longer the string, the longer they take.
string.h Functions in Action
strcpy and strcat don't check if the destination is big enough. If you copy a 100-character string into a 10-character buffer, it happily overwrites whatever memory comes after β corrupting data, crashing, or creating a security hole. Use strncpy and strncat with an explicit size limit, or better yet, use snprintf.Character Functions
Individual characters have their own toolkit in <ctype.h>:
toupper('a')returns'A'tolower('Z')returns'z'isdigit('5')returns non-zero (true)isalpha('x')returns non-zero (true)
Remember: a char in C is just a small integer. 'A' is 65, 'a' is 97, '0' is 48. You can do math on characters!
Manual Iteration and Character Functions
String Literals vs. Char Arrays
There's a subtle but important difference:
char name[] = "Alice";β creates a mutable array on the stack. You can change characters.char *name = "Alice";β points to a read-only string literal stored in a special section of memory. Modifying it is undefined behavior.
If you need to modify the string, use the array form. If you just need to read it (like passing to printf), a pointer to a literal is fine.