Tuesday, July 14, 2009

C pointers, give practical examples?

Pointer is a variable that contains the address of another variable. (or in other words the address of a memory location). in 16-bit segmented memory model, there are two types of pointers: near pointer, that points in the same memory segment, and far pointer, which can point to beyond the current memory segment. Near pointer is actually a 16-bit integer that addresses a memory location in the segment pointed to by DS register of processor. While far pointer is 32-bit integer which contains both segment and offset address.





in 32-bit flat addressin mode, pointer is always a 32-bit integer.





One important thing to understand is pointer itself does not contain any data (or code sometimes), rather it contains the address of a memory location where data (or code) can be found. Using this technique is called indirect addressing and multiple indirection could be possible.





I give hereunder a code example which uses the pointers. Two operators in C are very important when using pointers. * is called 'value at' and %26amp; is called 'address of'. here's the code in C:





#include %26lt;conio.h%26gt;


#include %26lt;stdio.h%26gt;





void main()


{


int x=100;


int *ax=%26amp;x;





printf("%d, %d", x, *ax); // will print 100, 100


printf("%d",ax); //will print memory address of x





*ax=200; // you are actually changing x with its pointer ax





printf("%d, %d", x, *ax); // will print 200, 200


printf("%d",ax); //will print memory address of x





}





try this code in a 16-bit C version.


hope that answers the question

C pointers, give practical examples?
pointer is a variable it stores the address of another variable.





say for example


you are declaring a variable integer





int i;


i=10;


int occupies 2 bytes in the memory


say for example


memory address will look like this





8000 8001 8002 8003 ......9000





when you store it in the memory it will converted to binary and occupies the 2 bytes





here int i will occupie from 8000 to 8016





int *ptr;





ptr=%26amp;i (address of i)





so now ptr contains the starting address of i ...


here i starting address is 8000. so ptr= 8000





*ptr = value at address ( 10)


%26amp;i = address of i (8000)


%26amp;ptr= address of ptr ( prt is also variable so it will occupy some space in memmory it will return that base address





for better understanding





buy the book named "pointers in c " by yaswant kanithkar


No comments:

Post a Comment