📌 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)