# C Programming language

Day 7 Pointer arithmetic in C Programming language
 Previous Home Next

## # Pointer arithmetic in C Programming language

Arithmetic operations on a pointer is possible. There are four arithmetic operators that can be used on pointers: ++, --, +, and -

To understand pointer arithmetic, let us consider that ptr is an integer (Assuming 32-bit integers) pointer which points to the address 1000.

Let us perform the following arithmetic operation on the pointer:

```int *ptr;
ptr++;
```

After above operation, ptr will be point to the next location 1004. The reason behind that, each time ptr incremented and it will located to next integer which is 4 bytes ( i.e. 1004) next to previous location (i.e. 1000). This operation doesn’t impact on actual value at memory location, Means value at memory location not changed.

In case of char:
```char *ptr;
ptr++;
```

If ptr points to a character whose address is 1000, then above operation will point to the location 1001 because next character will be available at 1001.

## # Incrementing a Pointer

```#include <stdio.h>

const int MAX = 3;

int main ()
{
int  variable[] = {10, 100, 200};
int  i, *ptr;

/* let us have array address in pointer */
ptr = variable;
for ( i = 0; i < MAX; i++)
{

printf("Address of variable[%d] = %x\n", i, ptr );
printf("Value of variable[%d] = %d\n", i, *ptr );

ptr++;/* move to the next location */
}
return 0;
}
```
Output

Value of variable[0] = 10
Value of variable[1] = 100
Value of variable[2] = 200

## # Decrementing a Pointer

```#include <stdio.h>

const int MAX = 3;

int main ()
{
int  variable[] = {10, 100, 200};
int  i, *ptr;

/* let us have array address in pointer */
ptr = variable;
for ( i = 0; i < MAX; i++)
{

printf("Address of variable[%d] = %x\n", i, ptr );
printf("Value of variable[%d] = %d\n", i, *ptr );

ptr--;/* move to the next location */
}
return 0;
}
```
Output

Value of variable[0] = 200
Value of variable[1] = 100
Value of variable[2] = 10

## # Pointer Comparisons

Pointers may be compared by using relational operators, such as ==, <, and >.

```#include <stdio.h>

const int MAX = 3;

int main ()
{
int  var[] = {10, 100, 200};
int  i, *ptr;

ptr = var;
i = 0;
while ( ptr <= &var[MAX - 1] )
{

printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );

ptr++;
i++;
}
return 0;
}
```