# Pointer arithmetic in C programming language

Here we will learn how pointer arithmetic works with pointer variables?

Here, we are taking an example with an integer array; we will declare an integer pointer and initialize the pointer with the base address of integer array.

Consider this example and read the explanation written below the program and output

## C program with pointer arithmetic (++) using int array, pointer of array

```#include <stdio.h>
int main(){
//declare an arra
int arr[]={10,20,30,40,50};
//declare and initialise pointer
int *ptr=arr;

printf("arr value: %d, memory address: %p\n",*ptr,ptr);
++ptr;
printf("arr value: %d, memory address: %p\n",*ptr,ptr);
++ptr;
printf("arr value: %d, memory address: %p\n",*ptr,ptr);
++ptr;
printf("arr value: %d, memory address: %p\n",*ptr,ptr);
++ptr;
printf("arr value: %d, memory address: %p\n",*ptr,ptr);

return 0;
}
```

Output

```arr value: 10, memory address: 0x7fffb273d9f0
arr value: 20, memory address: 0x7fffb273d9f4
arr value: 30, memory address: 0x7fffb273d9f8
arr value: 40, memory address: 0x7fffb273d9fc
arr value: 50, memory address: 0x7fffb273da00
```

### Explanation

In this program, each ++ (increment) expression is adding 1 to the pointer variable (ptr) but pointer variable (ptr) is not moving 1 byte.

Why?

When we add 1 to the pointer, pointer moves sizeof(pointer_data_type) bytes.

For example - if there is an integer pointer and we add 1 into the pointer will move sizeof(int) i.e. 2 or 4 bytes (depends on the system architecture).

In this example pointer variable ptr is an integer type and the sizeof(int) is 4 hence pointer is moving 4 bytes on each ++ operation and accessing the next values from array arr.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates