C Pointers and Arrays

๐Ÿ“Œ 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;
}
  

Try It Now

๐Ÿ’ก Explanation

  • ptr = numbers; makes the pointer point to the first array element.
  • *(ptr + i) accesses elements just like numbers[i].

๐Ÿง  Pointer vs Array Access

Both of these mean the same thing in C:

  • arr[i]
  • *(arr + i)
  • *(ptr + i) if ptr = 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)