C++ pointers are
special variable that contains the address of ordinary variable of its type. If
you a define a pointer of float type then, it can only stores the address of
float type variable. C++ pointer is
very important concept.
Pointer Notation
float a = 5.2;
The above statement tells the c++
compiler that,
(1) It reserves a memory block, that can only contains float value.
(2) Name
of that memory block is a, so we can access that memory block by variable a.
(3) Value
5.2 is stored in that memory block.
Computer selects a memory location to
store 5.2, this memory location is also known as address.
We can store this memory location in a
special variable called pointer variable.
float a = 5.2;
float *b;
b = &a;
Here b is a pointer variable that stores
the memory address of variable a.
* symbol
is used for declaring a pointer variable.
Value at address operator
C++ has a pointer operator called value
at address operator. It is represented as '*' operator.
At the time of pointer variable declaration, it has different meaning.
Value at address operator gives the
value stored at specified address.
Value at address operator is also known
as indirection operator.
See the following code:
float a = 5.2; //line 1
float *b;
//line 2
b = &a;
//line 3
cout<<*b; //line 4
OUTPUT:
5.2
Program to Illustrate C++ Pointers
#include <iostream>
using namespace std;
int main()
{
int a = 1;
float b = 2.1;
char c = 'A';
int *p;
float *q;
char *r;
cout<<"Value
of a = "<<a<<"\nAddress of a =
"<<&a;
cout<<"\nValue
of b = "<<b<<"\nAddress of b =
"<<&b;
cout<<"\nValue
of c = "<<c<<"\nAddress of c =
"<<&c;
cout<<endl<<endl;
p = &a;
q = &b;
r = &c;
cout<<"Value
of a = "<<*p<<"\nAddress of a = "<<p;
cout<<"\nValue
of b = "<<*q<<"\nAddress of b = "<<q;
cout<<"\nValue
of c = "<<*r<<"\nAddress of c = "<<r;
return 0;
}
OUTPUT:
Value of a = 1
Address of a = 0x28fef0
Value of b = 2.1
Address of b = 0x28feec
Value of c = A
Address of c = Aff♠@☺
Value of a = 1
Address of a = 0x28fef0
Value of b = 2.1
Address of b = 0x28feec
Value of c = A
Address of c = Aff♠@☺
0 comments:
Post a Comment