Nearby lessons

92 of 124

C - Pointer Arithmetics

Learn pointer arithmetic in C — adding to a pointer moves it forward by the size of the type it points to, which is how you walk through arrays with a pointer.

What is Pointer Arithmetic?

You can add integers to a pointer. p + 1 does not move 1 byte — it moves forward by the size of the type the pointer points to. For an int pointer that is sizeof(int) bytes, so p + 1 lands exactly on the next integer.

In simple words: pointer arithmetic follows the type size — p + 1 on an int pointer skips 4 bytes (one whole int), not 1 byte.

Walking an Array with a Pointer

Because the array name is the address of the first element, *(p + i) reaches element i — exactly like a[i]:

Example02
CCode Cell
1#include <stdio.h>
2void main() {
3 int a[5] = {10, 20, 30, 40, 50};
4 int *p = a; // p points to a[0]
5 int i;
6 printf("a[0] via *p : %d\n", *p);
7 printf("a[1] via *(p+1) : %d\n", *(p + 1));
8 printf("Whole array: ");
9 for (i = 0; i < 5; i++) {
10 printf("%d ", *(p + i)); // same as a[i]
11 }
12 printf("\n");
13}
Output
a[0] via *p      : 10
a[1] via *(p+1)  : 20
Whole array: 10 20 30 40 50

Pointer Increment (p++)

You can also move a pointer forward step by step with p++ inside a loop:

Example03
CCode Cell
1#include <stdio.h>
2void main() {
3 int a[4] = {5, 10, 15, 20};
4 int *p = a;
5 int i;
6 for (i = 0; i < 4; i++) {
7 printf("%d ", *p);
8 p++; // move to the next element
9 }
10 printf("\n");
11}
Output
5 10 15 20

Rules to Remember

  • Adding to a pointer moves by the size of the pointed-to type.
  • *(p + i) and p[i] mean the same thing.
  • Pointer subtraction tells how many elements are between two addresses.
  • Do not add two pointers — that is meaningless.
📝 Key Takeaways
  • p + 1 on an int pointer moves by sizeof(int) bytes
  • *(p + i) reaches the element at index i
  • Pointer arithmetic is how arrays are traversed internally

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2