C/C++

# Pointer Arithmetic in C++ With Programming Examples

## Pointer Arithmetic:

Pointer Arithmetic in C++:- We can perform two arithmetic operations on pointers. These are addition and subtraction operations. Pointer arithmetic in c++ may be incremented or decremented. It means that we can add or subtract integer value to and from the pointer. Similarly, pointer arithmetic can be subtracted ( or added) from another.

The addition and subtraction operation on pointers are different than that of ordinary arithmetic operations. The following set of statements explains the pointer arithmetic in c++:

Int *p;

Int x;

P=&x;

P++;

Suppose the memory address allocated to variable â€˜xâ€™ is 200 which is assigned to â€˜pâ€™. both â€˜pâ€™ and â€˜xâ€™ are of int type. The size of the int type is 2 bytes. When the statement p++ is executed, the contents of p will be 202 (instead of 201). When an integer is added or subtracted from a pointer, the pointer in not incremented or decremented by that integer but is incremented or decremented by integer times the size of the object to which the pointer refers. The size of the object depends upon its data type. So the statement p++ will be evaluated as:

200+1*2=202

Each time pointer arithmetic in c++Â  is incremented, it points to the memory location of the next element of its base type. Similarly, each time it is decremented, it points to the location of the previous element. In the case of pointers to characters, the increment and decrement operations are performed as normal.

However, all the other pointer variables are incremented or decremented by the size of the data type they point to. For example, pointer variable â€˜ppâ€™ that points to â€˜floatâ€™ data type, hold the memory address 4000, and value 2 is added to it as:

pp=pp+2;

after executing the above statement, the value 4008(4000+2*4 = 4008) will be assigned to pp.

A pointer can be assigned to another one if both the pointers are of the same type. Otherwise, a cast operator must be used to convert the value of the pointer on the right side of the assignment operator (=) to the pointer type on the left side of the assignment operator.

## Related Article:

https://programmingdigest.com/searching-in-c-sequential-searching-binary-searching/

Check Also
Close