C Pointer Subtraction šŸŽÆ

beginner
22 min

C Pointer Subtraction šŸŽÆ

Welcome back to CodeYourCraft! Today, we're diving into a fascinating aspect of C programming - Pointer Subtraction. This concept is crucial for navigating memory and understanding dynamic data structures. Let's get started! šŸŽ‰

Understanding Pointers šŸ“

Before we delve into pointer subtraction, let's refresh our memories on what pointers are. In C, a pointer is a variable that stores the memory address of another variable.

c
int num = 10; int *ptr = # // ptr now holds the memory address of num

Pointer Arithmetic šŸ’”

Pointer arithmetic allows us to perform arithmetic operations on pointers. We can increment or decrement a pointer, which moves it to the next or previous memory location, respectively.

c
int arr[] = {1, 2, 3, 4, 5}; int *ptr = arr; // ptr points to the first element of arr ptr++; // ptr now points to the second element

Pointer Subtraction šŸŽÆ

Pointer subtraction is an extension of pointer arithmetic, which gives us the difference between two pointers in memory. This is especially useful when dealing with arrays and dynamic memory allocation.

c
int arr[] = {1, 2, 3, 4, 5}; int *ptr1 = arr; int *ptr2 = arr + 3; // ptr2 points to the fourth element int distance = ptr2 - ptr1; // distance now holds 3

šŸ’” Pro Tip: Pointer subtraction gives the number of elements between two pointers pointing to an array, not their memory addresses!

Pointer to Pointer šŸ“

You can have pointers to pointers, which allows for multi-dimensional arrays and dynamic memory allocation of arrays.

c
int **array; // array is a pointer to a pointer to an integer array = (int*) malloc(sizeof(int*) * 3); // allocate memory for 3 pointers for (int i = 0; i < 3; i++) { array[i] = (int*) malloc(sizeof(int) * 3); // allocate memory for 3 integers for (int j = 0; j < 3; j++) array[i][j] = i * 3 + j; }

Pointer Subtraction with Pointers to Pointers šŸŽÆ

With pointers to pointers, pointer subtraction works similarly. It gives the number of sub-arrays between two pointers pointing to a multi-dimensional array.

c
int **array = ...; // initialized multi-dimensional array int **ptr1 = array; int **ptr2 = array[2]; // ptr2 points to the third sub-array int subArrays = ptr2 - ptr1; // subArrays now holds 1

Practice Time šŸ’”

Now, let's test your understanding with a few exercises.

Quick Quiz
Question 1 of 1

What does pointer subtraction return for two pointers pointing to different arrays?

Quick Quiz
Question 1 of 1

What does the following code do?