Monday, January 25, 2021
Home C / C++ Pointers in C++

Pointers 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;
  6. int main()
  7. {
  8.  int a; // a is an integer
  9.  int *aPtr; // aPtr is a pointer to an integer
  11.  a = 7;
  12.  aPtr = &a; // aPtr assigned address of a
  14.  cout << “The address of a is “ << &a
  15.  << “nThe value of aPtr is “ << aPtr;
  17.  cout << “nnThe value of a is “ << a
  18.  << “nThe value of *aPtr is “ << *aPtr;
  20.  cout << “nnShowing that * and & are inverses of “
  21.  << “each other.n&*aPtr = “ << *&aPtr
  22.  << “n*&aPtr = “ << *&aPtr << endl;
  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.


- Advertisment -

Most Popular

Android Webview Tutorial With Example | How to Use Webview in Android

Android Webview Tutorial With Example Have you seen an Android app displaying Web content using Webview. This Android Webview Tutorial is about integrating Webview using Android Studio....

Student Registration Project in PHP

In this Student Registration Project we are providing a form in simple html to the student and that form sends the data to "student.php"...

Java GUI Calculator Source Code

Here we have a Java GUI Calculator Source Code for you in which a Java GUI calculator has been created using "swing" and "awt". The calculator has...

Numeric Array in PHP

Numeric arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero....