C++ Pointers and References

Spread the love

int var = 10;

int *ptr;

ptr = &var;

std::cout << “Address of var is ” << &var << std::endl;

std::cout << “Value of var is ” << *ptr << std::endl;


Why we need C++ Pointers and References

C++ pointers are not difficult to learn. In truth, there are a few C++ tasks that are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, which are almost impossible to do without our pointy friends.

As we have been trying to beat into your head, every variable is a memory location and every memory location has an address.

Each of these specific addresses can be accessed by using the ampersand (&) operator. Code below will print the address of the variables of integer mAnt and the char array of mAnt2. 


#include <iostream>
using namespace std;
int main () {
   int  mAnt;
   char mAnt2[15];

   cout << "Address of mAnt variable: "
        << &amp;mAnt << endl;

   cout << "Address of mAnt2 variable: "
        << &amp;mAnt2 << endl;

   return 0;
}

Address of mAnt variable: 0x7c1b1ed8138c

Address of mAnt2 variable: 0x7c1b1ed81390


So now that we have finished with Addresses, can we move on?

Yeah, but not really. Lets take a look at our Pointy friends but this doesn’t mean that we are finished with Addresses otherwise known as C++ References, right?


C++ Pointers – What’s up with these, anyway?

A C or C++ pointer is a variable of X type that points to an Address or Reference. Oh my gosh, so we aren’t finished with Addresses yet? Ok, so how does this work then?

int var = 20;
int *ptr;
ptr = &var;
std::cout << "Address of var = " << &amp;var << std::endl;
std::cout << "Value at ptr = " << *ptr << std::endl;


C++ Pointer Sample Code

#include <iostream>
using namespace std;
int main () {
   int  mAnt = 20;
   int *pmAnt; // a pointer of int type can point to another int
   
   // point the pointer to the address of int type called mAnt
   pmAnt = &mAnt; 

   // Print the hex of the address for mAnt
   cout << "Address of mAnt variable: " << &amp;mAnt << endl;

   // Dereference the pointer to get to its content
   cout << "Content of pmAnt pointer: " << *pmAnt << endl;

   return 0;
}

Address of mAnt variable: 0x7bde02b2516c

Content of pmAnt pointer : 20


Homework — Point yourself at your References

  • 1) The first example above is really short. Please memorize
  • 2) From memory rewrite the code above into your c++ compiler/editor
  • 3) Change the variables names. Ours were intentionally made silly. A good pointer name is ptr
  • 4) Then do the whole thing again. Yep, pointers are that important

Next Lesson 9, C++ Pointer to a Char Array

Top