Search⌘ K
AI Features

Solution: Dynamic Warehouse Inventory

Understand how to dynamically allocate and manage warehouse inventory data in C++ using heap memory. Explore safe memory practices such as using new[], delete[], and setting pointers to nullptr to prevent errors and ensure program stability.

We'll cover the following...
C++ 23
#include <iostream>
int main() {
int size = 0;
std::cin >> size;
// Allocate memory on the heap for 'size' integers
int* inventory = new int[size];
// Read input into the dynamic array
for (int i = 0; i < size; ++i) {
std::cin >> inventory[i];
}
// Calculate total
int totalItems = 0;
for (int i = 0; i < size; ++i) {
totalItems += inventory[i];
}
std::cout << "Total items in warehouse: " << totalItems << "\n";
// Deallocate the memory block
delete[] inventory;
inventory = nullptr; // Good practice to nullify pointer after delete
return 0;
}
Did you find this helpful?
...