Pointers in C++

0
206
Dynamic Memory allocation in C++
Functions in C++

Pointers in C++ are the variables that contain memory addresses as their values. Normally, a variable directly contains a specific value. A pointer contains the memory address of a variable that, in turn, contains a specific value. In this sense, a variable name directly references a value, and a pointer indirectly references a value.  Referencing a value through a pointer is called indirection. In the given example we will see how to declare and use a pointers in C++:

  1. // pointers in C++.
  2. //difference b/w * and & operator
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8.  int a; // a is an integer
  9.  int *aPtr; // aPtr is a pointer to an integer
  10.  
  11.  a = 7;
  12.  aPtr = &a; // aPtr assigned address of a
  13.  
  14.  cout << “The address of a is “ << &a
  15.  << “nThe value of aPtr is “ << aPtr;
  16.  
  17.  cout << “nnThe value of a is “ << a
  18.  << “nThe value of *aPtr is “ << *aPtr;
  19.  
  20.  cout << “nnShowing that * and & are inverses of “
  21.  << “each other.n&*aPtr = “ << *&aPtr
  22.  << “n*&aPtr = “ << *&aPtr << endl;
  23.  
  24.  return 0;
  25. }

In the start of main we defined an integer variable and assigned a value of 7 to it. then we defined a pointer which then directs to the integer. If we print “aptr”, it will be actually the address of the integer, if we use a “*” with it then it will print the value at the address of the variable which is 7. Here the ” & ” operator is used for address and ” * ” is used for the value at that address and these both are inverse of each others and cancels the effects of each others.Here the use of pointers is not so cleared but it will be obvious in Dynamic Memory Allocation.

 

Dynamic Memory allocation in C++
Functions in C++

Leave a Reply