A reason for why to take a pointer of different data type .

 why to take a pointer of different data type.


for eg if we take in c and cpp we generally take the pointer variable of the type ,of which variable's address we want to store in it.

for pointer it is fixed that it reserves 2 bytes for it then why is it so....??

As far as pointer is concerned we store an int variables address so we have to take a pointer tf int variable type there is a simple reason behind it .

for a pointer variable,has nothing to do with what is the type of variables whose address is going to be stored in it. Remember the the two points always keep in mind it that pointer requires only two bytes & is stored always in RAM, 

Lets take an example

class A
{
     int a;
     int *ptr;
//(*) sign is to indicate that it is not a normal variable but a pointer variable.

     ptr=&a;//stores an address of int variable a

}

now see we took int pointer variable so we indicate the pointer variable that we are going to store the address of variable of integer type just to indicate it we took the pointer variable of integer data type.

well what happens by doing this......?    why are we doing like this as it is fixed that it requires two bytes well the reason is at the time of derefrencing the varuiable yess its a crucial thing at the time of derefrencing and looks what type of pointer is declared and than derefrences it..So it knows that how much data it should read. For example derefrencing a char pointer should read the next byte from the address it is pointing to,while an integer pointer should read two bytes.

Still getting in detail The reason why you need the data type for pointers is because the compiler has to know what the size of the memory cell is.

still having doubts then i have a better way to make u understand see in pointer when u declare *ptr 

and want to store the refrence of variable say int a now suppose address of the variable is 1000 to 1002 so what happens is its starting address is only stored in the pointer variable now at the time of de-allocation pointer only knows its starting address then how much to move forward becomes a question mark for the pointer. so if we declare the poinyter of int data type then it knows from the starting address to move two bytes .


by this concept i hope the doubts would get cleared...!!!!!


Comments

Popular posts from this blog

State space search / blocks world problem by heuristic approach /TIC TAC TOE

Navigation in Vaadin.

Drag and drop items from one Grid to another