Address Arithmetic

PropellerAds

If p is a pointer to some element of an array, then p++ increments p to point to the next element,
and p+=iincrements it to point ielements beyond where it currently does. These and similar
constructions are the simples forms of pointer or address arithmetic. All types of arithmetic
operations are not possible with pointers.

The valid operations that can be performed using pointers are
(i) Addition of an integer to a pointer and increment operation.
(ii) Subtraction of an integer from a ponter and decrement operation.
(iii) Subtraction of a pointer from another pointer of same type.

The arithmetic operations that cannot be performed on pointers are as follows
(i) Addition, multiplication and division of two pointers.
(ii) Multiplication between pointer and any number.
(iii)Division of a pointer by any number.
(iv) Addition of float or double values to pointers.

The expression p+1 yields the correct machine address for the next variable of that type. Other
valid pointer expressions:
p+i, ++p, p+=I, p-q
where p-q represents the No of array elements between p and q.
Since a pointer is just a mem address, we can add to it to traverse an array.
p+1 returns a ptr to the next array element.

Precedence level of * operator and increment/decrement operators is same and their associativity
is from right to left. In reality, p+1 doesn’t add 1 to the memory address, it adds the size of the
array element.

Suppose p is an integer pointer and x is an integer variable. Now the main problem is to identify
how the following pointer expressions given below are interpreted.

(i) x = *p++ is same as two expressions x = *p followed by p = p + 1.
(ii) x = (*p)++ is same as two expressions x = *p followed by *p = *p + 1.
(iii) x=*++p is same as two expressions p=p+1 followed by x=*p.
(iv) x=++*p is same as two expressions *p=*p+1 followed by x=*p

Try Now – Programming In C MCQs