initialize dynamic array c++ to 0
#include <iostream>
int main() {
int size;
std::cout << "Enter the size of the array: ";
std::cin >> size;
int* arr = new int[size](); // Step 1
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " "; // Step 2
}
delete[] arr; // Step 3
return 0;
}
Step 1: Dynamic array initialization
In this step, we declare a pointer variable arr
of type int*
. We use the new
keyword to dynamically allocate memory for an integer array of size size
. The ()
at the end of the new int[size]
expression initializes all elements of the array to zero. This is done by default for arrays of built-in types like int
.
Step 2: Accessing array elements
In this step, we iterate over the elements of the dynamically allocated array using a for
loop. The loop runs from index 0 to size-1
. Inside the loop, we use the arr[i]
syntax to access each element of the array and print its value.
Step 3: Deallocating memory
In this step, we use the delete[]
operator to deallocate the memory that was dynamically allocated for the array. This is important to prevent memory leaks. The []
after delete
indicates that we are deallocating an array and not just a single object.
We use the delete[]
operator because we used the new[]
operator to allocate memory for the array. If we had used new
instead of new[]
, we would have used delete
instead of delete[]
to deallocate the memory.
By deallocating the memory, we free up the resources that were used by the array, making them available for other parts of the program.