Pointers in C++

C++ pointers are very simple and easy to learn. The pointer is used in c++ so that tasks can be performed more easily.Pointers are symbolic representation of addresses.The pointer is used to enable the program and to create and manipulate dynamic memory allocation where programmers don't have to worry about how much memory they will need to assign for each task, which cannot be done/performed without the concept of a pointer.

A proper definition of a pointer is a variable whose value is the address of another variable. Just like any other variable, we must declare a pointer before using it.

Syntax

type *var-name;

Where type is pointer base type
var-name is the name of the pointer variable
Asterisk is used to declare a pointer.

Example

char   *s;     // pointer to character
int    *p;    // pointer to an integer
float  *r;    // pointer to a float
double *q;    // pointer to a double



Example Of Pointers:

#include <bits/stdc++.h> 
using namespace std; 
void lfc() 
{ 
int var = 10;  
//declare pointer variable     
int *ptr;  
//note that data type of ptr and var must be same 
ptr = & var;     
// assign the address of a variable to a pointer 
cout << "Value at ptr = " << ptr << "\n"; 
cout << "Value at var = " << var << "\n"; 
cout << "Value at *ptr = " << *ptr << "\n";      
} 
//Driver program 
int main() 
{ 
lfc(); 
} 


Output :

Value at ptr = 0x7ffcb9e9ea4c
Value at var = 10
Value at *ptr = 10

Advantages of using Pointers in C++

There are many advantages to using pointers in C ++, some of them are:

1. Pointers make possible to return more than one value from the function.
2. Pointers save the memory.
3. Pointers increase the processing speed.
4. Pointers allow passing of arrays and strings to functions more efficiently.
5. Pointers reduce the length and complexity of a program.

Exercise:-

1. The operator used for dereferencing or indirection is ____?

A. *
B. &
C. ->
D. –>>

View Answer


2. Which one of the following is not a possible state for a pointer.

A. hold the address of the specific object
B. point one past the end of an object
C. zero
D. point to a type

View Answer



Program :-

C++ implementation of References

#include <iostream>
using namespace std;
int main()
{
int i;
double d;
int &a=i;
double &b=d;
i=20;
d=0.97;
cout<<"Value of original  int variable i:"<< i<< endl;
cout<< "Value of reference int variable a:"<< a<< endl;
cout<<"Value of original  double variable d:"<< d<< endl;
cout<<"Value of reference  double variable b:"<< b<< endl;
return 0;
} 


Output :

Value of original  int variable i:20
Value of reference int variable a:20
Value of original  double variable d:0.97
Value of reference  double variable b:0.97





Visit :


Discussion



* You must be logged in to add comment.