C Pointer Arithmetic

Pointer Arithmetic in C:

C pointers can be defined as a variable, pointing towards the address of a value. C also facilitates Arithmetic operations with Pointers. Some of these are:

C Pointer Increment:

Incrementing a pointer in C simply means to increase the pointer value step by step to point to the next location.

Logic:

Next Location = Current Location + i * size_of(data type)

Example 1: Example for C Pointer Increment.

#include<stdio.h>
 
void main()
{  
int n = 10; 	 
int *a;
a = &n;  
printf("current address = %x \n",a);
a = a+1;
printf("next address = %x \n",a);
}

Output

current address = 5deb5ffc
next address = 5deb6000

C Pointer Decrement:

Decrementing a pointer in C simply means to decrease the pointer value step by step to point to the previous location.

Logic:

Next Location = Current Location – i * size_of(data type)

Example 2: Example for C Pointer Decrement.

#include<stdio.h>
 
void main()
{  
int n = 10; 	 
int *a;
a = &n;  
printf("current address = %x \n",a);
a = a-1;
printf("next address = %x \n",a);
}

Output

current address = d460f58c
next address = d460f588

C Pointer Addition:

Addition in pointer in C simply means to add a value to the pointer value.

Logic:

Next Location = Current Location + (Value To Add * size_of(data type))

Example 3: Example for C Pointer Addition.

#include<stdio.h>
 
void main()
{  
int n = 10; 	 
int *a;
a = &n;  
printf("current address = %x \n",a);
a = a + 4;
printf("next address = %x \n",a);
}

Output

current address = bfdcd58c
next address = bfdcd59c

C Pointer Subtraction:

Subtraction from a pointer in C simply means to subtract a value from the pointer value.

Logic:

Next Location = Current Location – (Value To Add * size_of(data type))

Example 4: Example for C Pointer Subtraction.

#include<stdio.h>
 
void main()
{  
int n = 10; 	 
int *a;
a = &n;  
printf("current address = %x \n",a);
a = a - 2;
printf("next address = %x \n",a);
}

Output

current address = f2fd491c
next address = f2fd4914
Please follow and like us:
Content Protection by DMCA.com