In this lesson, we'll delve into the fascinating world of Pointer Arithmetic in C language. Understanding pointer arithmetic is crucial to mastering memory management and working with dynamic data structures. By the end of this session, you will be able to navigate through memory locations efficiently using pointers.
Pointer arithmetic is an operation that involves adding or subtracting integers to a pointer variable, which allows us to move forward or backward within the memory address space pointed to by the pointer.
*
): Accessing the value stored at the memory location pointed to by a pointer.&
): Used to get the memory address of a variable.#include <stdio.h>
int main() {
int array[5] = {0, 1, 2, 3, 4};
int *ptr;
ptr = &array[0]; // Assign the address of first element to pointer
printf("Array Elements:\n");
for(int i=0; i<5; i++) {
printf("%d ", *(ptr+i)); // Pointer arithmetic to access elements of array
}
return 0;
}
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
char *ptr = str;
while(*ptr != '\0') { // Traverse through the string
printf("%c ", *ptr);
ptr++; // Increment pointer to move to the next memory location
}
return 0;
}
Segmentation fault
)What causes it: Accessing an invalid memory address using a pointer.
#include <stdio.h>
int main() {
int *ptr = NULL;
*ptr = 5; // Attempt to write to memory location pointed by NULL pointer
}
Solution: Validate the memory address before using it with pointers.
#include <stdio.h>
int main() {
int *ptr = malloc(sizeof(int)); // Allocate memory for an integer
if (ptr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
*ptr = 5;
}
Why it happens: Attempting to access an uninitialized or non-existent memory location.
How to prevent it: Always check if the pointer points to a valid memory address before using it.
Out of bounds array access
)What causes it: Accessing elements outside the boundaries of an array or dynamic data structure using pointers.
#include <stdio.h>
int main() {
int array[5] = {0, 1, 2, 3, 4};
int *ptr = &array[0];
printf("%d\n", *(ptr+5)); // Accessing element beyond the bounds of the array
}
Solution: Ensure that the pointer index never exceeds the size of the data structure.
#include <stdio.h>
int main() {
int array[5] = {0, 1, 2, 3, 4};
int *ptr = &array[0];
int arrSize = sizeof(array)/sizeof(array[0]); // Calculate the array size
for (int i=0; i<arrSize; i++) {
printf("%d ", *(ptr+i)); // Accessing elements within the bounds of the array
}
}
Why it happens: Improper handling of data structure boundaries.
How to prevent it: Calculate and validate the index when using pointer arithmetic with arrays or dynamic data structures.
Next steps for learning: Dive deeper into dynamic memory allocation and managing memory efficiently in larger C programs.