It is a variable used to store address of another variable. Pointer data type is the type of variable who address is stored.
Examples
Pointer type |
Stores |
integer type pointer |
integer variable address |
character type pointer |
character variable address |
Float type pointer |
Float variable address |
Double type pointer |
Double variable address |
Pointer Syntax
data_type *pointer_name;
Program |
Output |
#include
using namespace std;
int main( ){
//Pointer declaration
int *p, var=101;
//Assignment
p = &var;
cout<<"Address of var: "<<&var<
cout<<"Address of var: "<
cout<<"Address of p: "<<&p<
cout<<"Value of var: "<<*p;
return 0;
}
|
Address of var: 0x7fff5dfffc0c
Address of var: 0x7fff5dfffc0c
Address of p: 0x7fff5dfffc10
Value of var: 101
|
Pointer and arrays
To create a pointer for array assigning the address of array to pointer don’t use ampersand sign(&).
p = arr;// Incorrect:
p = &arr; ;// correct:
Example: Traversing the array using Pointers
Program |
Output |
#include
using namespace std;
int main() {
int *p;
int arr[]={1, 2, 3, 4, 5, 6};
p = arr;
for(int i=0; i<6;i++) {
cout<<*p<
//++ moves pointer to next int position
p++;
}
return 0;
}
|
1
2
3
4
5
6
|
Pointers to Objects
Pointer can point to objects. Pointer is created to a object using a ‘*’ operator in front of a class.
Program to create a object pointers |
Output |
#include
#include
using namespace std;
class student
{
private:
int empno;
string name;
public:
student():empno (0),name(""){}
student(int r, string n): empno(r),name (n)
{}
void get()
{
cout<<"enter empno ";
cin>> empno;
cout<<"enter name";
cin>>name;
}
void print()
{
cout<<" empno is "<< empno;
cout<<"name is "<
}
};
int main ()
{
student *ps=new student;
(*ps).get();
(*ps).print();
delete ps;
return 0;
}
|
enter roll no10
enter namewisdom
roll no is 10name is wisdom
|
Pointers to Class Members
Pointers to class member functions and member variables van also are done.
Program |
Output |
#include
using namespace std;
#include
class Simple
{
public:
int a;
};
int main()
{
Simple obj;
Simple* ptr; // Pointer of class type
ptr = &obj;
cout << obj.a;
cout << ptr->a; // Accessing member with pointer
}
|
32766 32766
|
class Data
{
public: int a;
void print()
{ cout << "a is "<< a; }
};
int main()
{
Data d, *dp;
dp = &d; // pointer to object
int Data::*ptr=&Data::a;
// pointer to data member 'a'
d.*ptr=10;
d.print();
dp->*ptr=20;
dp->print();
}
|
a is 10
a is 20
|
this pointer in c++
It is used to represent the address of an object inside a member function. It will hold the address of object obj inside the member function method().
Program |
Output |
#include
#include
using namespace std;
class sample
{
int a,b;
public:
void input(int a,int b)
{
this->a=a+b;
this->b=a-b;
}
void output()
{cout<<"a = "<
};
int main()
{
sample x;
x.input(5,8);
x.output();
getch();
return 0;
}
|
a = 13
b = -3
|
|