Array Pointer Arithmetic in C

Level 5282 keystrokes

Shows that arr[i] and *(ptr + i) read the same element by printing both for each index of {10, 20, 30, 40, 50}. It then walks the array by incrementing the pointer itself and prints 10 20 30 40 50.

C code

// Five ints stored next to each other
1int arr[] = {10, 20, 30, 40, 50};
// The array name converts to a pointer to its first element
2int *ptr = arr;
3
// Prints a heading for the comparison
4printf("Array access vs pointer:\n");
5for (int i = 0; i < 5; i++) {
// ptr + i moves i elements (not bytes) forward, so both forms print the same value
6 printf("arr[%d]=%d, *(ptr+%d)=%d\n", i, arr[i], i, *(ptr + i));
7}
8
// Prints an empty line and a second heading
9printf("\nPointer increment:\n");
// arr + 5 points just past the last element, so the loop stops there
10while (ptr < arr + 5) {
// *ptr++ reads the current element, then moves ptr to the next: 10 20 30 40 50
11 printf("%d ", *ptr++);
12}
// Ends the output line
13printf("\n");

Output

Array access vs pointer:
arr[0]=10, *(ptr+0)=10
arr[1]=20, *(ptr+1)=20
arr[2]=30, *(ptr+2)=30
arr[3]=40, *(ptr+3)=40
arr[4]=50, *(ptr+4)=50

Pointer increment:
10 20 30 40 50
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ,× 10
  • "× 10
  • ;× 9
  • (× 9
  • )× 9
  • +× 7
  • \× 5
  • %× 5
  • =× 5
  • *× 4

More C examples at level 5

← C typing practice