Basic Dynamic Memory Allocation
Create a program that dynamically allocates memory for a single integer, assigns a value to it, then prints the value. Remember to free the allocated memory to avoid memory leaks.
Hint
Use the new operator to allocate memory for an integer.
Use the delete operator to free the allocated memory.
Answer
#include <iostream>
int main() {
// Allocate memory for an integer
int* ptr = new int;
// Assign a value to the integer
*ptr = 42;
// Print the value of the integer
std::cout << "The value of the dynamically allocated integer is: " << *ptr << std::endl;
// Free the allocated memory
delete ptr;
return 0;
}