C Pointer Arithmetic
In C language we can perform five arithmetic operations on pointers.
Example:
Similarly as we can increment pointers, we also can decrement them by
Similarly we can perform subtraction on pointers.
Subtraction of two pointers tell us how far they are from each other. The resulting subtraction is of the type size_t which is an unsigned integer. It gives number of objects or elements between two pointers.
Pointers cannot be multiplied or divided.
- Increment (++)
- Decrement (--)
- Addition (+)
- Subtraction (-)
- Differencing
Increment and Decrement
When a pointer of specific data type (int, char, float etc) is incremented by an integral value i the new value will be calculated by following formula,(current address in pointer) + i * sizeof(data_type)
Example:
int a=10; int *p1; p1=&a; p1++; p1--;Here we declared a variable
a
which occupies 2 bytes in memory. Suppose it has address 1000. So address of next int type memory location will be 1002, since int occupies 2 bytes memory. p1++;
do this job.Similarly as we can increment pointers, we also can decrement them by
p1--;
.
Addition and Subtraction
In C we can add or subtract integers from pointers.int *p1,score; p1=&score; p1=p1+4;Here the pointer will point to fourth integer memory location from current one. Suppose currently
p1
is holding 1000 i.e address of score variable. Then fourth integer memory location from 1000 is calculated as (current address in pointer)+i*sizeof(data_type)
i.e 1000+4*sizeof(int)
which equals 1000+8=1008, the address of fourth integer type memory location from current one.Similarly we can perform subtraction on pointers.
Differencing
Differencing of pointers means subtraction of two pointers.Subtraction of two pointers tell us how far they are from each other. The resulting subtraction is of the type size_t which is an unsigned integer. It gives number of objects or elements between two pointers.
int *p1,*p2,score; p1=&score; p2=p1+2; printf(" %d ",p2-p1);In above example we assigned address of score to p1. Then assigned p2 with address of third block from p1. Output is 2. This is because both pointers point to integer data types and difference between them is two objects.
Pointers cannot be multiplied or divided.