In this post, we are going to discuss pointers. But before proceeding, I just want to say that if you really followed all my posts till now then, Congratulations! You learned the basics of programming in general!
But there are still a lot of basics in C++! C++ is a very old programming language but we still use it because of the fact that C++ is the only language to have very high performance with object-orientation. The term, ‘object orientation’ is a very broad term which we will not discuss in this series.
C++ is powerful because it is a very low-level language. And when something is low level, it will be way more flexible but hard to work with. With the help of C++, we can access every bit of our device memory directly. And so, this direct access needs us to be cautious of how it works and what are we really doing with it.
A pointer is the memory address of a variable. I don’t want to say that but learning pointers is a hard thing! Although the definition may look so simple, to work with pointers isn’t that simple. However, if we understand the way pointer works and all such concepts, it will all be a piece of cake!
Getting the memory address of a variable:
int main()
{
//As we all know, a basic variable of type 'int'
int value = 20;
//To get the memory address of any variable,
//put ampersand(&) at the back of a variable's name.
//This prints a hexadecimal value which
//represents the memory address of the variable
cout << &value << endl;
return 0;
}
It looks useless but it is very useful! The memory address of a variable is that address inside our device memory where that particular variable is stored. It is a hexadecimal value which is something that is not important to know about. Here is a link explaining what is hexadecimal.
POINTER CONCEPT:
If two variables have same memory addresses, they will act like one variable. Or in other words, a variable can not have two different memory addresses. If we think that a variable have two different memory addresses, they will act like two variables.
Filling a pointer with the memory address of a variable:
//A basic variable of type 'int'
int value = 20;
//Pointer declaration is just like references
//except that it has an asterisk(*) instead of the ampersand(&)
//A pointer to type 'int'
int* pValue = &value;
//'pValue' is a pointer to 'value'
//or 'pValue' contains the memory location of 'value'
cout << pValue << endl;
cout << &value << endl;
//Both gives us the same memory address
Yup! There is a bit of confusion regarding where to use ampersands, asterisks and other symbols while working with pointers and references. But once we got used to it, it will get easy!
That’s it for now! We will discuss it more later. For now, it is quite much to get used to. No, pointers are not useless! Keep proceeding. Pointers are not a hard subject! I was joking!