Search⌘ K
AI Features

Solution: Dynamic Warehouse Inventory

Explore how to implement dynamic memory management in C++ to store and manage warehouse inventory data efficiently. Learn to allocate arrays on the heap, safely access elements, and properly free memory with delete[]. Understand the importance of setting pointers to nullptr to prevent memory errors and ensure robust code.

We'll cover the following...
C++ 23
#include <iostream>
int main() {
int size = 0;
std::cout << "Enter number of batches: ";
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::cout << "Enter count for batch " << (i + 1) << ": ";
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;
}
...