New & Delete Operators
Lesson 11 of 14 in Coddy's C++ Pointers course.
The last important thing you must learn about pointers is dynamic memory allocation.
Dynamic memory allocation allows memory to be allocated during runtime. This means that you don't need to declare and initialize variables when using pointers before the program starts, we can allocate space in the memory for something that will be used later on.
For that, we use the keyword new.
int *ptr; // Declaring a pointer
// Allocating memory for 1 int:
ptr = new int; // ptr points to that memoryBy using new we essentially reserve room in our memory for one integer that we can use later on.
But, for memory leaks not to happen which we will cover in the next lesson, every memory we allocate by using new we should delete before the end of the program by using the keyword delete.
int *ptr;
ptr = new int;
*ptr = 10;
cout << "*ptr = " << *ptr << endl;
delete ptr; // Free up allocated memoryAs you can see, by using the keyword delete the memory we allocated for the pointer ptr we later on delete and that space in the memory is now deallocated and free. In the next lesson, you will learn about the importance of memory leak control.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyDynamically allocate memory for three integers using the pointers ptrA, ptrB, and ptrC. Use the three integers given as the function's arguments and set the values at the pointer address to equal the integers respectively. First integer to ptrA, the second integer to ptrB , and the last integer to ptrC, and finally print out all of the pointers dereferenced and separated with a whitespace
Do NOT write the <i>main()</i> function
Try it yourself
#include <iostream>
using namespace std;
void dynamicMemory(int a, int b, int c) {
// Enter your code here
}
// Do NOT write the main() functionAll lessons in C++ Pointers
2Pointers & References
Pointers as ParametersReferences - &References as ParametersPointers vs References