1️⃣ Dynamic Memory Allocation Example
📌 Explanation: new
is used to allocate memory dynamically, and delete
is used to free the allocated memory.
#include <iostream>
using namespace std;
int main() {
int* ptr = new int; // Allocating memory for an integer
*ptr = 42; // Assigning value
cout << "Dynamically allocated value: " << *ptr << endl;
delete ptr; // Freeing memory
return 0;
}
📝 Output:
Dynamically allocated value: 42
2️⃣ Creation & Deletion of a Dynamic Array
📌 Explanation: We allocate an array dynamically using new
and release it using delete[]
.
#include <iostream>
using namespace std;
int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;
int* arr = new int[size]; // Dynamic memory allocation for array
// Assigning values
for (int i = 0; i < size; i++) {
arr[i] = (i + 1) * 10;
}
// Displaying values
cout << "Array values: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
delete[] arr; // Freeing dynamically allocated array
return 0;
}
📝 Output (Example for size = 5):
Enter the size of the array: 5
Array values: 10 20 30 40 50
3️⃣ Dynamic 2D Array Allocation & Deletion
📌 Explanation: Allocating and deallocating a 2D array dynamically.
#include <iostream>
using namespace std;
int main() {
int rows = 3, cols = 3;
// Dynamic allocation of 2D array
int** arr = new int*[rows];
for (int i = 0; i < rows; i++) {
arr[i] = new int[cols];
}
// Assigning values
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = (i + 1) * (j + 1);
}
}
// Displaying values
cout << "2D Array values: " << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
// Deleting allocated memory
for (int i = 0; i < rows; i++) {
delete[] arr[i];
}
delete[] arr;
return 0;
}
📝 Output:
2D Array values:
1 2 3
2 4 6
3 6 9
Let me know if you need more examples! 🚀
0 Comments