Saturday 31 August 2013

Pointer Arithmetic | C Language Study Material pdf



Pointer Arithmetic:

An integer operand can be used with a pointer to move it to a point / refer to some other address in the memory.
consider an int type ptr as follows
Assume that it is allotted the memory address 65494 increment value by 1 as follows .
mptr ++;             or   ++ mptr;
mptr = mptr +1;  or   mptr + =1 ;
++ and - - operators are used to increment, decrement a ptr and commonly used to move the ptr to next location. Now the pointer will refer to the next location in the memory with address 64596.
C language automatically adds the size of int type (2 bytes) to move the ptr to next memory location.
mptr  = mtpr + 1
         = 645.94 + 1 * sizeof (int)
         = 65494 + 1 * 2
Similarly an integer can be added or subtract to move the pointer to any location in RAM. But the resultant address is dependent on the size of data type of ptr.
The step in which the ptr is increased or reduced is called scale factor.Scale factor is nothing but the size of data type used in a computer.
We know that in a pc,
The size of float = 4
char = 1
double = 8 and so on
Ex: float *xp; (assume its address = 63498)
xp = xp + 5;
Will more the ptr to the address 63518
? 63498 + 5 * size of (float0
? 63498 + 5*4
? 63498+20
? 63518

Rules for pointer operation:
The following rules apply when performing operations on pointer variables
1. A pointer variable can be assigned to address of another variable.
2. A pointer variable can be assigned the values of another pointer variables.
3. A pointer variable can be initialized with NULL or 0 value.
4. A pointer variable can be prefixed or postfixed with increment and decrement operator.
5. An integer value may be added or subtracted from a pointer variable.
6. When 2 pointers points to the same array, one pointer variable can be subtracted from another.
7. when two pointers points to the objects of save data types, they can be compared using relational .
8. A pointer variable cannot be multiple by a constant.
9. Two pointer variables cannot be added.
10. A value cannot be assigned to an arbitrary address.

0 comments:

Post a Comment

 

C Programming Language Interview Questions and Answers Tutorial for beginners. Copyright 2013 All Rights Reserved