๐ C Pointers & Arrays
In C, arrays and pointers have a close bond โ almost like siblings. An array name acts like a pointer to its first element, and pointers can be used to access array elements!
๐น How Are Arrays and Pointers Connected?
When you write arr[0]
, it’s equivalent to *arr
. That’s because arr
is a pointer to the first element of the array.
๐ Example: Accessing Array Elements via Pointer
Letโs walk through an example to see this pointer-array friendship in action.
#include <stdio.h> int main() { int numbers[] = {5, 10, 15, 20, 25}; int *ptr = numbers; for (int i = 0; i < 5; i++) { printf("numbers[%d] = %d, *(ptr + %d) = %d\n", i, numbers[i], i, *(ptr + i)); } return 0; }
๐ก Explanation
ptr = numbers;
makes the pointer point to the first array element.*(ptr + i)
accesses elements just likenumbers[i]
.
๐ง Pointer vs Array Access
Both of these mean the same thing in C:
arr[i]
*(arr + i)
*(ptr + i)
ifptr = arr
๐ ๏ธ Practice Time!
Try this out with a char
or float
array. Use pointer notation to print out the elements!
๐ Summary
- Array names act like pointers to their first element.
- You can use pointer arithmetic to traverse arrays.
arr[i]
is the same as*(arr + i)