In C programming language, pointer arithmetic is the process of performing arithmetic operations on pointers. Pointer arithmetic is useful for navigating through arrays, manipulating strings, and working with dynamically allocated memory.
When performing arithmetic operations on a pointer, the size of the data type that the pointer points to is taken into account. For example, if a pointer points to an integer variable, incrementing the pointer by 1 will actually increment it by the size of an integer.
Here are some examples of pointer arithmetic in C:
int arr[] = {1, 2, 3, 4, 5}; int *ptr = arr; // ptr points to the first element of the array // accessing array elements using pointer arithmetic printf("%d\n", *ptr); // prints 1 printf("%d\n", *(ptr + 1)); // prints 2 printf("%d\n", *(ptr + 2)); // prints 3 // incrementing a pointer ptr++; // ptr now points to the second element of the array printf("%d\n", *ptr); // prints 2 // decrementing a pointer ptr--; // ptr now points back to the first element of the array printf("%d\n", *ptr); // prints 1 // subtracting two pointers int *ptr2 = &arr[3]; // ptr2 points to the fourth element of the array printf("%d\n", ptr2 - ptr); // prints 3, which is the difference between the two pointers
In this example, we declare an integer array named “arr” and a pointer named “ptr” that points to the first element of the array. We then use pointer arithmetic to access the elements of the array, increment and decrement the pointer, and find the difference between two pointers.
Pointer arithmetic can also be used with character arrays and strings. Here’s an example of how to use pointer arithmetic to manipulate a string:
char str[] = "Hello, world!"; char *ptr = str; // ptr points to the first character of the string // printing the string using pointer arithmetic while (*ptr != '\0') { printf("%c", *ptr); ptr++; }
In this example, we declare a character array named “str” that contains a string, and a pointer named “ptr” that points to the first character of the string. We then use pointer arithmetic to print the string character by character, by incrementing the pointer until it points to the null terminator character ‘\0’.
Pointer arithmetic in C is a powerful feature that enables the programmer to work with arrays, strings, and dynamically allocated memory. However, it should be used carefully to avoid errors such as accessing out-of-bounds memory or dereferencing invalid pointers.