Topic : A primer on Pointers
Author : saradhi
Page : << Previous 2  
Go to page :


integer variable occupies two bytes in memory the statement ii=&i  stores only the addresses of the first byte. Similarly ff = &f stores only the addresses of first byte out of four bytes occupied by the float variable f.



The address of the first byte is often known as the base address. Though ii and ff contain only the base addresses, the expressions *ii and *ff allow access to all the bytes occupied by the integer i and f respectively.



Consider the following program.



main()

{

int  n=32;

float f = 3.14



char *ii, *ff;

ii = &n;

ff = &n;



/*note that ii and ff are pointer to characters*/



printf(“Address contained in ii = %u\n”,ii);

printf(“Address contained in ff = %u\n”,ff);

printf(“Value at address contained in ii = %d\n”,*ii);

printf(“Value at address contained in ff = %d\n”,*ff);



}



Observe carefully that here ii,ff have been declared as char pointers. Still the statements ii= &n and ff = &n work.



However the program falters at the printf()s. This is so since ii is a char pointer and *ii will give the 1 byte value at address contained in it, which is definitely not the 2 byte integer value of n. Same is the case with ff.



The moral is that if you wish to access an integer value stored in a variable using its address it’s necessary that the address be stored in an integer pointer. Likewise, if you wish to access a float value stored in a variable using its address its necessary to store the address in a float pointer.



Note: Since I ran all the programs on a 16bit Borland C compiler my integer size is 2 bytes. In case of 32bit GNU compiler on UNIX platform size of integer is 4 bytes. Check the size of int on your compiler to avoid discrepancies between your and my results.



The following program will print the size of int on you machine.



main()

{

printf(“%d”,sizeof(int));

}





Good Bye

Indurthi VijayaSaradhi




Page : << Previous 2