Memory of a program :
The memory of a program in C++ is composed of 2 units :
1. Stack : A static memory and we kinda define its size before the program executes.
2. Heap : A dynamic memory. It is most beneficial when you have various inputs and you can't define their size before execution.
What is a pointer?
A pointer stores the address of a variable. For example,
int a = 5; // variable
int* a_pointer = &a; //* differentiates it as a pointer. & is used to get the address.
Now we have stored the address of 'a' variable in 'a_pointer'. Moreover, if you cout 'a_pointer' then you'll have the same output as in case of cout << &a that is the address of 'a' variable.
int* serves as the data type for a pointer of type int.
If you want to print the data stored in 'a' using 'a_pointer', you can do it by using * while printing i.e.
cout << *a_pointer;
Similarly, if you are upto storing the address of a char data type then :
char b = 'X';
char* b_pointer = &b;
cout << b_pointer; //address of b is displayed
Remember that pointer of any data type is of 4 bytes despite the fact that it is char, int or float. Address are displayed as 8 characters hexadecimal number.
Note : & and * are opposites of each other. This means :
int a = 5;
cout << *(&a); //Displays the data in 'a' since & and * have cancelled out with each other.
Similarly, you can store the address of a pointer into another pointer as :
int A = 5;
int* A_ptr = &A;
int** A_ptr2 = &A_ptr;
Now in this case, As we moved onto a pointer who was pointing a another pointer, we got int**. Likewise, a third-stage pointer would be int*** and goes on!
In the next part, we'll discuss arrays as pointers.
Comment below if you have any confusions. Thanks! :)
0 comments:
Post a Comment