Pointers (1)
Course: C++ Part 2 - chapter 2
Memory Allocation
Section titled “Memory Allocation”https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQvyknTBoEOmrY2ILIabG4EzpDGsMSqr6PiQsnIRko4yw&s
💡 Statically declared arrays (i.e arrays whose size is fixed and known at compile time) are stored in Stack memory
Variables whose size is determined at run time i.e dynamic sized variables are stored in heap memory. For example, dynamic sized arrays are stored in heap memory. Basically, whatever is created at run time uses heap memory. And the variables whose size are fixed and known at compile time are created in stack memory.
What are pointers?
Section titled “What are pointers?”
Pointers store the address of a variable. The address it stores can be either of a stack memory or heap memory.
int x = 10; // We define an integer variable. It gets assigned 4 bytes in stack memoryint *ptr = &x; // We create a pointer on variable x. The pointer (ptr) stores the address of x💡
&is the addressOf operator when used on the **right hand **of an=sign and can be used for defining references if used on left hand side or in function arguments. Similarly,*operator generally is used as valueOf operator except when it is declared with a data type in front of it, in that case it is for declaring a pointer variable.
💡 In C++, references just means aliases (alternative name) to existing variables. They do not occupy any memory.
We can directly modify values of variables using pointers. For example,
int x = 10;int *ptr = &x; // We create a pointer on x*ptr = 20; // Updates the value of x to 20.Note, in the above example the usage of * operator. In the second line we have int *ptr = &x; . This tells us to create a pointer and assign it the value of address of variable x.
In Line 3, we write *ptr = 20 . As mentioned above, * without a data type before it is considered as valueOf operator. So it is read as:
Set valueOf variable pointed by pointer ptr (i.e x) to 20.
Data type of pointer
Section titled “Data type of pointer”Pointers themselves are always integers / longs as they hold memory location. They generally occupy a size of 8 bytes (or 4 bytes for 32-bit system)
However, we might see the different types of pointers are defined depending on the data type whose address it holds.
For example we define int *ptr for pointers holding address of integer variables. Similarly, we define double *ptr for pointers holding address of double variables. But the type of the pointer only signifies what is the data type of the variable whose address it holds and does not have anything to do with its memory allocation.
Pointer of Pointer
Section titled “Pointer of Pointer”It is a pointer to some pointer, i.e stores address of a variable which is a pointer.
int x = 10;int *ptr = &x; // ptr stores address of xint *ptr1 = &ptr; // ptr1 stores address of ptrcout<< *ptr1; // Prints address of xcout<< **ptr1; // Prints value of x