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! š
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.
int num = 10;
int *ptr = # // ptr now holds the memory address of numPointer 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.
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 elementPointer 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.
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!
You can have pointers to pointers, which allows for multi-dimensional arrays and dynamic memory allocation of arrays.
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;
}With pointers to pointers, pointer subtraction works similarly. It gives the number of sub-arrays between two pointers pointing to a multi-dimensional array.
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 1Now, let's test your understanding with a few exercises.
What does pointer subtraction return for two pointers pointing to different arrays?
What does the following code do?