Use of Pointers in C++
- A pointer is a variable that holds a memory address.
Declaring a pointer
Eg:- int *k or int* k
Pointer operators
*<PointerName> - to obtain the value of the variable the pointer is pointed to
Eg: *k
&<Pointer/VariableName> - to obtain the memory address of the pointer or the variable
Eg: &k
Assigning a value
int *m; //declaring the pointer
int num=2; //declaring the variable
m=# //assigning the memory address of 'num' to the pointer 'm'
Consider the following program
#include <iostream>
using namespace std;
int main ()
{
int var1=11;
int var2=12;
int *ptr1, *ptr2, *ptr3;
ptr1=&var1; //memory address of var1 is assigned to ptr1 or ptr1 is pointed to var1's location
ptr2=&var2; //memory address of var2 is assigned to ptr2 or ptr2 is pointed to var2's location
ptr3=ptr2;
cout<< *ptr1 << "\t" << *ptr2<< "\t" << *ptr3 << endl; //11 12 12
ptr2=ptr1; //memory address of var1 is assigned to ptr2
cout<< *ptr1 << "\t" << *ptr2<< "\t" << *ptr3 << endl; //11 11 12
*ptr1=*ptr3; // the value of ptr3 is assigned as the value to ptr1
cout<< *ptr1 << "\t" << *ptr2<< "\t" << *ptr3 << endl; //12 12 12
return 0;
}
Comments
Post a Comment