Sie sind auf Seite 1von 3

# There are 2 things to be learnt in pointers. 1. & 2. * Now, & is the 'address of' operator.

So, if you write cout<<&p;, it means that the memory location of the variable p will be printed out(hexadecimal nos). Now, there is a data type type*. For eg, int* r declares a variable r of the data type int*. Now the variables of this data type are actually a means of storage of memory locations ie. the variable r will just be used to store the memory location(address of some other variable). The twist is *r will be the value stored in the location towards which r will pe 'pointing'. So, int p; int*r; r=&p; is a totally valid function. (Think!) So here, the variable r is said to be the pointer to the variable p. In general, the variables of the type T* are said to be pointer variables of the type T. Now, int* p and int *p are both the same and the * always seems to associate itself only with p and never with int. This means, int* p,q; means p is a pointer variable and q is just an int variable. Now, for understanding, the operator * (the de-referencing operator) actually is to be read as 'the content of'. So, *xyz means 'the content of the variable xyz. So, if you write int p; int* r; r=&p; *r=15;, you will be actually making a

change in the value stored at the memory location of p ie. it is equivalent to writing p=15;. Now using pointers in functions int cartesian_to_polar(float x,float y, float* r, float* theta) { *r=sqrt(x*x+y*y); *theta=atan2(x,y);}

## int main() { float x,y,ptheta,pr; cin>>x>>y; cartesian_to_polar(x,y,&pr,&ptheta); cout<<pr<<ptheta; return 0; }

Think about the above program once. How the parameter data-types match in the declaration and the calling of the function. In the declaration, float* is the type ie., we are having an arrow(pointer) as the parameter and the input variable will be an address which is given by &pr and &ptheta. So, the swap program using call-by-reference method will be--void swap(int* a, int* b) { int temp; temp=*a; *a=*b; *b=temp;} And it will be called as swap(&x,&y);

Array name by itself---The important question is whether we are allowed to use the name of an array all by itself without specifying the index. It

turns out that C++ allows us to use it. The array name ALL BY ITSELF actually is the ADDRESS of the first element of the array! So, in effect it is a pointer to the first element of the array!! int array[56]; Then array is effectively of the type int* This property is extremely important when we want to pass on the array as a parameter for a function. So, suppose we want to calculate the sum of the elements of an int array via a function call. int sum{int* b,int n} { int t=0; for(int i=0;i<n;i++) { return t; } sum(a,5); Look closely! We arent using &a as the argument. This is because a is by itself the pointer that is of the type &v! t+=b[i];}