The next major milestone in C after mastering the relationship between Arrays and Pointers is Strings.
In C, a string is not a built-in data type like int or float. Instead, it is simply a character array that ends with a special "sentinel" value called the null terminator (\0).
1. The Anatomy of a C-String
Because a string is an array, all the pointer logic you just learned applies here. The only difference is that the computer needs to know where the text ends.
- Declaration:
char name[] = "Syntax"; - Memory View:
['S', 'y', 'n', 't', 'a', 'x', '\0'] - The Null Terminator (
\0): This character has an ASCII value of 0. It tells functions likeprintfto stop reading memory. Without it, the computer would keep printing random data from your RAM.
2. Pointer Manipulation of Strings
Because a string is a pointer to the first character, you can navigate it very efficiently.
c
1#include <stdio.h>
2
3int main() {
4 char message[] = "Hello";
5 char *ptr = message; // Points to 'H'
6
7 // Printing using pointer movement
8 while (*ptr != '\0') {
9 printf("%c", *ptr);
10 ptr++; // Move to the next character (1 byte)
11 }
12
13 return 0;
14}3. String Literals vs. Character Arrays
This is a common point of confusion that involves pointers:
| Syntax | Type | Memory Location | Modifiable? |
char arr[] = "Hi"; | Array | Stack | Yes |
char *ptr = "Hi"; | Pointer to Literal | Read-Only Data | No (Changing it causes a crash) |
4. Essential String Functions (string.h)
C provides a library to handle the "dirty work" of moving pointers through character arrays:
strlen(str): Moves a pointer until it hits\0and returns the count.strcpy(dest, src): Uses pointers to copy characters from one memory location to another.strcmp(s1, s2): Compares strings character by character using pointer offsets.
Summary Checklist
- A string is just a
chararray. - It must end with
\0. - The name of the string is a pointer to the first character.
- Using
ptr++on a string moves exactly 1 byte at a time.
