
Pointer is used to allocate memory dynamically i.e. at run time. The variable might be any of the data type such as int, float, char, double, short etc.
Syntax :
To declare a pointer, we use an asterisk between the data type and the variable name
Pointers require a bit of new syntax because when you have a pointer, you need the ability to both request the memory location it stores and the value stored at that memory location.
data_type *ptr_name;
Example :
int *a; char *a;
Where, * is used to denote that ''a'' is pointer variable and not a normal variable.
In this context, the asterisk is not a multiplication
Key points to remember about pointers:
# Normal variable stores the value whereas pointer variable stores the address of the variable.
# The content of the pointer always be a whole number i.e. address.
# Always pointer is initialized to null, i.e. int *p = null.
# The value of null pointer is 0.
# & symbol is used to get the address of the variable.
# * symbol is used to get the value of the variable that the pointer is pointing to.
# If pointer is assigned to NULL, it means it is pointing to nothing.
# Two pointers can be subtracted to know how many elements are available between these two pointers.
# But, Pointer addition, multiplication, division are not allowed.
# The size of any pointer is 2 byte (for 16 bit compiler).
Since pointers only hold addresses, when we assign a value to a pointer, the value has to be an address. To get the address of a variable, we can use the address-of operator (&)
Example program for pointer:
#include
int main()
{
int *ptr, q;
  q = 50;
  /* address of q is assigned to ptr */
  ptr = &q;
  // prints address held in ptr, which is &q
  cout << ptr;
  /* display q's value using ptr variable */
  cout << *ptr;
  return 0;
}
The null pointer
ptr = 0;
// assign address 0 to ptr
or simply
int *ptr = 0;
// assign address 0 to ptr
C++ Pointer Arithmetic
Example :
ptr++;
ptr--;
ptr+21;
ptr-10;
If a char pointer pointing to address 100 is incremented (ptr++) then it will point to memory address 101
C++ Pointers vs Arrays
int main ()
{
int var[3] = {1, 2, 3};
int *ptr;
cout << *ptr << endl;
ptr++;
cout << *ptr << endl;
return 0;
}
this code will return :
1
2
C++ Pointer to Pointer
{
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;
return 0;
}
this code will return
Value of var :3000
Value available at *ptr :3000
Value available at **pptr :3000