0
0
C++programming~30 mins

Memory allocation and deallocation in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
Memory allocation and deallocation
📖 Scenario: Imagine you are managing a small library system where you need to store the number of books available in different sections. You want to learn how to create space in memory to store this data and then clean up the space when you are done.
🎯 Goal: You will write a simple C++ program that allocates memory dynamically for storing the number of books in three sections, assigns values to them, and then frees the memory.
📋 What You'll Learn
Use new to allocate memory for an array of integers
Assign values to the allocated memory
Use delete[] to free the allocated memory
Print the values stored in the allocated memory
💡 Why This Matters
🌍 Real World
Dynamic memory allocation is used in programs where the amount of data is not known before running the program, like managing lists of items or user inputs.
💼 Career
Understanding memory allocation and deallocation is essential for software developers to write efficient and safe C++ programs, especially in systems programming and game development.
Progress0 / 4 steps
1
Create a pointer and allocate memory
Create an integer pointer called books and allocate memory for 3 integers using new.
C++
Need a hint?

Use int* books = new int[3]; to allocate memory for 3 integers.

2
Assign values to the allocated memory
Assign the values 10, 20, and 30 to the first, second, and third elements of the books array respectively.
C++
Need a hint?

Use books[0] = 10; and similarly for the other elements.

3
Print the values stored in the allocated memory
Use a for loop with variable i from 0 to 2 to print each value in the books array separated by spaces.
C++
Need a hint?

Use a for loop and std::cout to print each element.

4
Deallocate the memory
Use delete[] books; to free the memory allocated for the books array. Then print a newline character.
C++
Need a hint?

Use delete[] books; to free the memory and then print a newline.