My Understanding of Pointers and References

After watching “A Pointers Primer” video and doing some research I feel like I have a grasp of Pointers now.

I use my favorite animated TV show Avatar The Last Airbender to explain pointers. I use a random number to determine how many avatars there were in the world of avatar.

Let’s start of with the Access Of Operator. This symbol “&” allows us to reference the address to another variable.

For instance we have

#include <iostream>

int main()
{
	int* Aang;
	int Korra;
	int Avatar;

	Avatar = 200;
	Aang = &Avatar;
	Korra = Avatar;
	
	
	std::cout << Aang << std::endl;
	std::cout << Korra << std::endl;
	

	return 0;
}

The amount of Avatars that have been in existence are 200.
We have the variable Aang which is dereferenced with * when called as a variable at the beginning of the main function.
Aang is equal to the address of Avatar. When complied the address of Aang is also the same address as Avatar.
When we call Korra we are getting just Avatar without it referencing anything so we get 200.

Now for the dereference operator. This * is used to point towards a variable.

#include <iostream>

int main()
{
	int* Aang;
	int Korra;
	int Avatar;

	Avatar = 199;
	Aang = &Avatar;
	
	Korra = *Aang;


	
	std::cout << Korra << " + 1 = 200. Korra is the 200th avatar!" << std::endl;

	return 0;
}

When we run the code Korra points to the address Aang which is equal to the address of Avatar. The * then takes the address of Avatar and finds that Avatar is equal to 199.

Now after getting the variable 199 I added it by one because she is the avatar after Aang.

In simple terms

A pointer is pointing to an address and accessing the address to find a variable.
A reference is the address.

2 Likes

Privacy & Terms