Pointer Expression

Pointer variable can be used in expressions like other variable. There are few following special aspects of pointer expressions.

  • • Pointer assignments
  • • Pointer Arithmetic
  • • Pointer comparisons

Pointer Assignments

In pointer assignment, a pointer variable can be used in the right hand side of the assignment statements to assign its value to another pointer. Let us consider ptr1 and ptr2 are two pointer variables of same type. Then the following statement

Ptr1 = ptr2;

is a valid statement.


Pointer Arithmetic

There are only two arithmetic operations allowed on pointer variables: addition and subtraction. C allows us to add integers to subtract integers from pointers, as well as to subtract one pointer from another. For example, if part1 and part2 are two pointer variables of same type, then the following expression

Ptr1+2
Ptr2-1
Ptr1-ptr2

Are valid. Let us assume ptr is pointer variable of integer type with the value 2001 and integers are of two bytes long. Then after the statement

ptr++;

the value of ptr will be 2003, not 2002. Each time ptr is incremented, it will point to next integer. The same is also true for decrements. If instead of previous statement, the statement could have been

ptr--;

Each time a pointer is incremented, it points to the location of the previous element. More generally, all pointer arithmetic will be done relative to the type of the pointer so that the pointer is always is pointing to the appropriate element.


Pointer Comparisons

In addition to pointer arithmetic, two pointers can be compared with each other by using relational operators. For example, two pointers could be compared to test for end of array or memory are could be compared to see if pointers reference to same object

if (ptr1> ptr2)      /* reached end? */
. . . 
if (ptr1 == ptr2)   /* same object? */


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext