Pointer Arithmetic in C

Level 4143 keystrokes

Demonstrates pointer arithmetic to access array elements.

C code

// Array of 5 ints stored next to each other in memory
1int arr[] = {10, 20, 30, 40, 50};
// The array name converts to a pointer to its first element
2int *ptr = arr;
3for (int i = 0; i < 5; i++) {
// ptr + i moves i elements (i * sizeof(int) bytes); * reads the value there
4 printf("%d ", *(ptr + i));
5}
// *(ptr + 2) is the same as arr[2], so it prints 30
6printf("\nThird: %d", *(ptr + 2));

Output

10 20 30 40 50 
Third: 30
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.

  • ,× 6
  • ;× 6
  • (× 5
  • )× 5
  • "× 4
  • +× 4
  • *× 3
  • =× 3
  • {× 2
  • }× 2

More C examples at level 4

← C typing practice