Saturday 24 March 2018

Pointer In C++

Pointer is a variable that points to an address of a value.
Pointers are used to access the memory and manipulate the address.
Pointer is used to allocate memory dynamically i.e. at run time. 
Pointer variable might be belonging to any of the data type such as int, float, char, double, short etc.
Reference operator (&) and Dereference operator (*)
& is called as reference operator (address of operator) which gives you the address of a variable.
(*) is called as dereference operator (indirection operator) which gives value from the address.
Advantage
Pointer reduces the code and improves the performance.
Uses:
We can dynamically allocate memory using malloc() and calloc() functions in pointer
Pointers are used in arrays, functions and structures. It reduces the code and improves the performance.
Syntax :
data_type *var_name;

Example 1:
 int *p;
 char *p;
Where * is used to denote that p is pointer variable .
Example 2:
 int x=5;
 int *p;
 p=&x

Important Points:
1.     Pointer variable stores the address of the variable.
2.    & symbol is used to get the address of the variable and *symbol is used to get the value of the variable that the pointer is pointing to.

Example:
#include <iostream>
using namespace std;
int main(){
int  x=50;
 int *p;    
 p=&x;//stores the address of number variable  
  cout<<"Value of variable var is:"<< x<<endl;
   cout<<"Value of variable var is:"<<*p<<endl;
   cout<<"Address of variable var is:"<<&x<<endl;;
   cout<<"Address of variable var is:"<<p<<endl;
  cout<<"Address of pointer p is:"<<&p<<endl;
return 0;
}  
Output:

Value of variable var is:50                                                                                                    
Value of variable var is:50                                                                                                    
Address of variable var is:0x7fff838b1804                                                                                      
Address of variable var is:0x7fff838b1804                                                                                      
Address of pointer p is:0x7fff838b1808 


No comments:

Post a Comment

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...