Wednesday, December 3, 2008

Playing wid Pointers

Defination->

Pointer are the
Derived Type Data Type,Which points to the address of the variable.

Common use of Pointer->

1.Accessing Array element.
2.Passing Argument to the function,when function need to modify original argument.
3.Obtaining memory from the system.
4.Creating Data structure like Link List

Address of operator & ->

The address of variable can be find using 'address of operator- &'
example :
int i;
int* ptr;
ptr=&i;
cout<<& i;

~ The Automatic variable are stored in stack,So while accessing address they appear in decending order.
~External variable address appear to be in acceding order,As they store in Heap.

@ There is difference in
'address of operator &' and 'reference operator &'
~ 'A of OP &' precedes a
variable name in a variable declaration.
~'R of OP &' follows type in in function prototype or definition.

example .... passing variable to function :-

void cal(int &); //prototype declaration for 'passing by reference'
void cal(int *) ;//prototype declaration for 'passing by address'

int var;
call(var);//passing by reference
call(&var);// passing by address

void call(int& v);//function definition in 'pass by reference'
void call(int* ptr)//function definition in 'pass by address'

~passing by reference mean passing an
alias of variable.
~While in pointer we pass address of variable.

int* PTR->
The asterisk means pointer to.
~We say variable PTR is pointer to Int.

Above we have said that pointer is Data type, then why we do not define the variable as
POINTER ptr; as in case of INT data type.

@ Reason-
becoz need to know kind of variable pointer points to, As compiler has to calculate the memory allocation as in case of array. Example is given below.


Accessing the Variable->
~ variable are access using its address rather than its name
Ex:
int i;
int* ptr;
ptr=& i;
cout<<*ptr;//value of variable will be display. *ptr -
when asterisk sign is used in front of variable name it is called indirect operator.
~
it mean value of variable pointed to by.Indirection operator some time also call dereference operator.

int *ptr//declartion: pointer to int
*ptr =3//indirect or dereference operator



No comments: