When I first started learning C++ a few years ago, the concept of “pointer” was a bit hard for me to understand. My main question was “why in the world would I EVER need them?” Today I understand their importance. Here’s a part of what I know about pointers:
- A pointer is like a special variable that holds an address of an another variable.
- There are 2 operators that you should remember when dealing with pointers:
1. “The content of” operator (*)
2. “The address of” operator (&) - A single address is 1 byte of memory in your PC.
- 1 byte is 8 bits of memory (a single bit can have either the value of 0 or 1).
- An address usually looks something like this: 0x205a
- Pointers store addresses, addresses store values.
- Let’s we have an integer named “MyVariable” and we want to store it’s address in a pointer:
int MyVariable = 5;
int* PtrVariable = &MyVariable; - Now we can refer to “MyVariable” through the pointer. How?
std::cout << *PtrVariable; - This would print out 5, since we are printing out “the content of” PtrVariable (remember the * operator as I described it above). We are in the process of “dereferencing” PtrVariable.
- Making statements like these:
std::cout << &MyVariable;
std::cout << PtrVariable; //No * operator
Would result in the same way. We would get the “address of” MyVariable (remember the & operator as described above). - You can have pointers to pointers to pointers to pointers (and so on), that hold addresses of pointers:
int** PtrPtrvariable; - You can use “references” (aka addresses) as parameters for functions:
void MyFunc(&a, &b); - Any changes made to the arguments while in the function will also leave a long-term effect on the variables that you’ve passed into the function.
- You can’t pass literals into these kind of functions (at least in the places where it requires a reference).
- You can have pointers as parameters:
void MyScndFunc(*a, *b); - Here you need to pass in addresses like so:
MyScndFunc(&SomeVariable, &SomeOtherVariable); - In order to access the content of “a” and “b”, you’ll need to dereference them which is more work, that’s why pass-by-reference is more preferred over pass-by-pointer.
- In most modern day compilers any pointer takes up 4 bytes (32 bits) of memory which is nice because you can save some memory.
- Pass by reference uses up less memory than pass by value, since the compiler doesn’t need to copy values. And also we should use a reference in the element declaration of the for each loop that we saw in section two (for optimization reasons):
for(auto &Letter : Word){ }
These are some of more important things that I know of pointers, there are a lot more which I could write up but I think that’s enough for now!