Pointers, arrays, and strings are closely connected in C. Understanding their relationship helps you master memory management, performance, and clean syntax.
📦Pointers and Arrays: The Relationship
🧠 In C, the name of an array is itself a pointer to the first element.
int arr[3] = {10, 20, 30};
printf("%p\\n", arr); // Address of arr[0]
printf("%p\\n", &arr[0]); // Same addressExpression | Meaning |
|---|---|
| Address of the first element of the array |
| Value at that address → |
| Value at |
| Same as |
✅ Example:
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // or &arr[0]
for(int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i)); // OR ptr[i]
}1 2 3 4 5📍 Memory Mapping of Arrays and Pointers
Let’s say:
int arr[3] = {5, 10, 15};Element | Address (assume) | Value |
|---|---|---|
arr[0] | 1000 | 5 |
arr[1] | 1004 | 10 |
arr[2] | 1008 | 15 |
arr→ 1000arr + 1→ 1004(arr + 2)→ 15
🔁 Pointer Arithmetic with Arrays
int arr[3] = {10, 20, 30};
int *p = arr;
printf("%d\\n", *p); // 10
printf("%d\\n", *(p+1)); // 20
printf("%d\\n", *(p+2)); // 30📌 Pointer arithmetic moves based on data type size
If int is 4 bytes → p+1 adds 4 bytes, not 1.
📬 Passing Arrays to Functions using Pointers
✅ Function Declaration:
void printArray(int *arr, int size);✅ Call:
int numbers[] = {1, 2, 3};
printArray(numbers, 3);✅ Function Definition:
void printArray(int *arr, int size) {
for(int i = 0; i < size; i++) {
printf("%d ", arr[i]); // or *(arr + i)
}
}👉 When you pass numbers, you're passing the address of the first element.
🧵 Strings and Character Arrays
A string in C is simply a char array ending with a null terminator '\\0'.
char str[] = "Hello";🧠 This is equivalent to:
char str[] = {'H', 'e', 'l', 'l', 'o', '\\0'};📌 Pointer to String
char *s = "Hello";This creates a pointer to a string literal. It is read-only — do not modify.
🔎 Accessing Characters in a String
char *s = "Hello";
printf("%c\\n", s[1]); // 'e'
printf("%c\\n", *(s + 4)); // 'o'Expression | Meaning |
|---|---|
| Address of first char |
| First character |
| Character at index i |
| Same as above |
⚠️ Beware of Pointer Modifications
char str[] = "C Lang";
char *p = str;
*p = 'D'; // ✅ Works (modifiable)
char *q = "C Lang";
*q = 'D'; // ❌ Undefined behavior (read-only)str[]→ modifiable"C Lang"→ stored in read-only memory
🧮 Traversing String Using Pointer
char *s = "World";
while (*s != '\\0') {
printf("%c ", *s);
s++;
}W o r l d🧪 Example: Reversing a String Using Pointers
void reverse(char *str) {
char *end = str;
while (*end) end++; // Move to end
end--; // Back from null terminator
while (str < end) {
char temp = *str;
*str = *end;
*end = temp;
str++;
end--;
}
}✅ Real-Life Usage
💬 Printing and manipulating strings
🔁 Passing arrays to functions efficiently
🛠️ Building custom versions of
strlen,strcpy, etc.🧪 Interview questions on pointer arithmetic