Arithmetic Operations on Pointers in C

Arithmetic Operations on Pointers in C

In this article, I am going to discuss Arithmetic Operations on Pointers in C with Examples. Please read our previous articles, where we discussed Pointers in C Language with Examples. At the end of this article, you will understand what are the different arithmetic operations we can perform on the pointer in C language.

Arithmetic Operations on Pointers:

Program:

#include<stdio.h>
int main ()
{
    int a, b, *p1, *p2, sum;
    printf ("Enter two integers to add\n");
    scanf ("%d%d", &a, &b);
    p1 = &a;
    p2 = &b;
    sum = *p1 + *p2;
    printf ("Sum of the numbers = %d\n", sum);
    return 0;
}

Output:

Arithmetic Operations on Pointers In C

Arithmetic Operations on Pointers In C with Examples

Pointers Rule:
Rule 1:
  • Address + Number // Address (Next Address)
  • Address – Number // Address (Pre-Address)
  • Address++ // Address (Next Address)
  • Address– // Address (Pre-Address)
  • ++Address // Address (Next Address)
  • –Address // Address (Pre-Address)
Rule 2:
  • Address-Address //Number (No. of elements) //size difference / size of (datatype)

Example:
int*p1=(int*)100
int*p2=(int*)200
p2-p1=50
200-100=100 / size of (int)

Rule 3:
  • Address + Address = illegal
  • Address * Address = illegal
  • Address / Address = illegal
  • Address % Address = illegal
Rule 4:

We can’t perform bitwise operation between 2 pointers like

  • Address & Address = illegal
  • Address | Address = illegal
  • Address ^ Address = illegal
  • ~Address = illegal
Rule 5:

We can use relational operator and conditional operator (<,>, <=,>=, ==, !=, ?:) between 2 pointers

  • Address > Address = T/F
  • Address >= Address = T/F
Rule 6:

We can find size of a pointer using size of operator.

Accessing value through pointer:

This can be done by using the indirection operator, so this operator is also known as value at the address operator.

Program:
#include<stdio.h>
void main()
{
 int a1;
 int*ptr;
 printf("Enter a value\n");
 scanf("%d", &a1);
 ptr=&a1;
 printf("\n%d", *ptr);
}

Output:

Accessing value through pointer

Pointer Conversions:

Suspicious pointer conversion: The warning message occurs when we are assigning the address of a variable in a different type of pointer. These conversions are not allowed in C++.

Non-portable pointer conversion: This warning message occurs when we are assigning value type data to a pointer.

Example:
void main()
{
 int a;
 int*ptr;
 ptr=a;
}

In the next article, I am going to discuss Pointer-to-Pointer in C language. Here, in this article, I try to explain Arithmetic Operations on Pointers in C. I hope you enjoy this Arithmetic Operations on Pointers in C article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *