Pointers: Arithmetic & Arrays
In C, pointers and arrays share a deep, fundamental relationship. The name of an array acts as a constant pointer to its first element.
1 Array Names as Constant Pointers
When you declare an array like `int arr[3] = {10, 20, 30};`, the symbol `arr` evaluates directly to the address of the first element (`&arr[0]`). This means:
- `*arr` evaluates to `arr[0]` (the first element).
- `*(arr + 1)` evaluates to `arr[1]` (the second element).
2 Pointer Arithmetic & Memory Step Sizes
When you increment a pointer (e.g. `ptr + 1`), C does not simply add 1 byte. Instead, it adds the **byte size of the data type** the pointer points to. For an `int` pointer (4 bytes), `ptr + 1` moves the address forward by exactly 4 bytes to point to the next integer in memory.
C — Pointers & Arrays
▶ Run Code
#include <stdio.h>
int main() {
int arr[3] = {10, 20, 30};
int *ptr = arr; // points to arr[0]
// Iterate using array offsets
printf("Iterating using pointer arithmetic:\n");
for (int i = 0; i < 3; i++) {
printf("Address at element %d: %p, Value: %d\n", i, (void*)(ptr + i), *(ptr + i));
}
// Traverse array by incrementing the pointer
printf("Traversing via pointer increment:\n");
printf("Value: %d\n", *ptr);
ptr++; // Moves to next integer (4 bytes forward)
printf("Value: %d\n", *ptr);
return 0;
}
3 Code Challenge
Challenge: Write a program that declares an array of 5 floating-point numbers. Create a pointer to the array, and print all values in reverse order by starting the pointer at the last index and decrementing it.