Welcome to another exciting lesson on C++ programming! Today, we're going to delve into the world of dynamic memory allocation using new[] and delete[]. These powerful operators are essential for managing memory efficiently in your C++ projects.
Dynamic memory allocation is a technique where we can request memory from the computer during runtime. This is particularly useful when the size of the data we need to store is not known at compile-time.
In C++, we have two operators, new[] and delete[], designed for dynamic memory allocation and deallocation of arrays. Here's a simple analogy to understand them better:
Think of a library where you can borrow multiple books (arrays) at once. When you're done, you have to return them all (deallocate) so that others can use them too.
To allocate memory for an array using new[], we use the following syntax:
int* myArray = new int[5];Here, we're creating an array of 5 integers and storing its address in myArray.
Pro Tip: Always initialize your pointers to nullptr before using new[] or delete[].
After we're done using the memory, we must return it to the system using delete[].
delete[] myArray;Remember, never forget to deallocate memory, as it can lead to memory leaks, which are bad for your program's health!
Let's create a simple program that stores and calculates the average of student scores using new[] and delete[].
#include <iostream>
int main() {
const int numStudents = 3;
int* scores = new int[numStudents];
// Input student scores
for (int i = 0; i < numStudents; ++i) {
std::cout << "Enter score for student " << i + 1 << ": ";
std::cin >> scores[i];
}
// Calculate and display the average
int total = 0;
for (int i = 0; i < numStudents; ++i) {
total += scores[i];
}
double average = static_cast<double>(total) / numStudents;
std::cout << "Average score: " << average << std::endl;
// Deallocate memory
delete[] scores;
return 0;
}Which operator in C++ is used for dynamic memory allocation of arrays?
We'll explore more advanced topics related to new[] and delete[] in future lessons. For now, practice using these operators to get comfortable with dynamic memory management in C++!
Happy coding! š