This example demonstrates how pointer arithmetic works with arrays. When arithmetic operations are performed on a pointer, the address changes based on the size of the datatype it points to.
#include <stdio.h>
int main()
{
int arr[] = {10, 20, 30, 40, 50};
int *ptr;
ptr = arr;
printf("ptr = %p\n", ptr);
printf("ptr + 1 = %p\n", ptr + 1);
printf("ptr + 2 = %p\n", ptr + 2);
printf("*ptr = %d\n", *ptr);
printf("*(ptr + 1) = %d\n", *(ptr + 1));
printf("*(ptr + 2) = %d\n", *(ptr + 2));
return 0;
}
Output:
ptr = 0x7ffc...
ptr + 1 = 0x7ffc...
ptr + 2 = 0x7ffc...
*ptr = 10
*(ptr + 1) = 20
*(ptr + 2) = 30
ptr points to the first element of the array.
When 1 is added to an integer pointer, the address increases by sizeof(int) bytes, not by 1 byte.
ptr + 1 points to the next integer element in the array.ptr + 2 points to the element after that.
Dereferencing the pointer using * accesses the value stored at that location.
Pointer arithmetic depends on the datatype associated with the pointer. The compiler uses the pointer type to calculate the correct memory offset.