C ยท Chapter 24 of 45

C Pointers and Arrays

Arrays and pointers are closely related in C: the name of an array can decay into a pointer to its first element in most expressions. This lets you use pointer arithmetic to move through array elements.

Understanding this relationship helps explain why array indexing like arr[i] is essentially equivalent to *(arr + i).

Syntax
int *p = arr;
*(p + i) == arr[i]

Array-to-pointer decay

When an array name is used in most expressions, it decays into a pointer to its first element. So `int *p = arr;` makes p point to arr[0] without needing &.

Pointer arithmetic

Adding an integer to a pointer moves it forward by that many elements (not bytes), based on the pointed-to type's size. `*(p + 1)` accesses the second element.

Example 1 (c)
#include <stdio.h>

int main() {
  int arr[3] = {10, 20, 30};
  int *p = arr;
  printf("%d\n", *(p + 1));
  return 0;
}
Output
20

p points to arr[0], so *(p + 1) accesses arr[1], which is 20.

Example 2 (c)
#include <stdio.h>

int main() {
  int arr[3] = {1, 2, 3};
  int *p = arr;
  for (int i = 0; i < 3; i++) {
    printf("%d ", *(p + i));
  }
  printf("\n");
  return 0;
}
Output
1 2 3 

Pointer arithmetic can traverse an array just like index-based access.

Key points

  • An array name decays into a pointer to its first element.
  • Pointer arithmetic advances by element size, not raw bytes.
  • arr[i] and *(arr + i) are equivalent expressions.
  • Arrays and pointers are related but not identical: sizeof behaves differently on each.
๐Ÿ’ก Note: Unlike a true array, a pointer variable can be reassigned to point elsewhere at any time.

๐Ÿ“ Quick Quiz

1. What does an array name decay into in most expressions?

2. What does *(arr + 2) access?

3. Can a pointer variable be reassigned to point to a different address?