Pointers in c++
A variable which holds the address of a memory location is called a pointer. It deals with memory.
To create a pointer variable, follow the syntax.
‘datatype *variable_name;’
Eg:
‘int *ptr;’
C++ Program:
This program includes the
built-in header file <iostream>. Next main() is defined.
It has following steps:
- A variable a is declared as integer. It reads the user input from command prompt.
- A pointer variable *ptr is declared.
#include <iostream>
using namespace std;
int main()
{
int
a;//Declaration of integer variable
int *ptr; //
Declarartion of pointer variable
// getting the
input from user
cout<<"Enter the variable:"<<endl;
cin>>a;
// storing address
of a in pointer myptr
ptr = &a;
cout <<
"Value of a is: ";
cout << a
<< endl;
// print the
address stored in ptr pointer variable
cout <<
"The Address stored in ptr is: ";
cout << ptr
<< endl;
cout <<
"Value of a using *ptr is: ";
cout << *ptr
<< endl;
return 0;
}
Output:
Enter the variable:
56
Value of a is: 56
The Address stored in ptr is: 0x7ffcb2dc4404
Value of a using *ptr is: 56
Consider the special feature called ‘this’ pointer .
‘this’ pointer:
It is
used to refers a current object reference.
Eg:
This->a=a;
Hope, you understood the concept of pointers. You can try
these concepts in float, double variables. Keep Coding!!!
Comments
Post a Comment