Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Arithmetic with Pointers

We can perform arithmetic operations with a pointer similar to the arithmetic operations with numeric values.
But in the case of pointers, there are some limitations.
Let’s assume that we are using a 32-bit machine for arithmetic operations with pointers.
Let’s see different types of arithmetic operations with pointers.

1) Incrementing a pointer

Example no 1

#include <stdio.h>
int main()
{
    int i=5;
    int *ptr1;
    ptr1=&i;
    printf("\n ptr1 points at = %d",ptr1);
    ptr1++;
    printf("\n After increment ptr1 points at = %d",ptr1);
    return 0;
}

Output

ptr1 points at = 2293316
After increment ptr1 points at = 2293320

In the above example, we can see that when the address of i is assigned to integer pointer ptr1, it points at address 2293316. But after the increment of pointer ptr1 by +1, ptr1 points directly at address 2293320 because ptr1 is an integer pointer. On 32bit machine integer pointer always increments by 4 bytes.
With pointers, arithmetic operations are not as that of normal arithmetic operations. It depends on the size of its data type.
On 32bit machine size of an integer is 4 bytes.

Example no 2

#include <stdio.h>
int main()
{
    double j=55.55;
    double *ptr2;
    ptr2=&j;
    printf("\n ptr2 points at = %d",ptr2);
    ptr2++;
    printf("\n After increment ptr2 points at = %d",ptr2);
    return 0;
}

Output

ptr2 points at = 2293312
After increment ptr2 points at = 2293320

In this example, pointer ptr2 is of double type. Therefore it increments by 8 bytes directly.

2) Decrementing a pointer

Example

#include <stdio.h>
int main()
{
    int k=8;
    int *ptr3;
    ptr3=&k;
    printf("\n ptr3 points at = %d",ptr3);
    ptr3--;
    printf("\n After decrement ptr3 points at = %d",ptr3);
    return 0;
}

Output

ptr3 points at = 2293316
After decrement ptr3 points at = 2293312

In this example, pointer ptr3 is of integer type. Therefore, it decrements by 4 bytes directly.

3) Subtraction of two pointers

C Programming Language Pointers Subtraction

Note

We can’t do Addition, Multiplication & Division among pointers.
Only Subtraction is allowed.

Pointer Comparison

Pointers can be compared with each other using relation operators such as, ==, <, >, <=, >=, !=.

Example

#include <stdio.h>
int main()
{
    int i=5;
    int *ptr1, *ptr2;
    ptr1=&i;
    ptr2=&i;
    if(ptr1==ptr2)
    {
        printf("\n Both pointers point to the same address");
    }
    else
    {
        printf("\n Both pointers point to the different address");
    }
    return 0;
}

Output

Both pointers point to the same address

 

Leave a reply