#include <iostream>
/**
* @brief This is the test for new and delete operator. And create a dynamic array.
*
* @return int
*/
int main() {
using namespace std;
int* pNumber = new int;
int * pNumber2 = pNumber;
delete pNumber2;
//delete pNumber; // We can not delete the same memory again, because it is already deleted.
cout.setf(ios_base::fixed, ios_base::floatfield); // fixed-point: six decimal places
cout << "Please the size of array:";
int n = 0;
cin >> n;
double* arr = new double[n];
for (int i = 0; i < n; i++) {
cout << "Please enter number" << i << ": ";
cin >> arr[i];
}
double sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
cout << "Sum: " << sum << endl;
cout << "Average: " << sum / n << endl;
delete [] arr;
return 0;
}
The main.cpp file contains a C++ program that creates a dynamic array and performs some operations on it. Here's a step-by-step explanation:
- The
main function starts by declaring a pointer pNumber and allocating memory for an integer using the new operator.
int* pNumber = new int;
- Another pointer
pNumber2 is declared and assigned the same memory address as pNumber .
int * pNumber2 = pNumber;
- The memory allocated to
pNumber2 is then deallocated using the delete operator. Note that the same memory cannot be deleted again, hence the commented out delete pNumber; .
delete pNumber2;
- The program then sets the output format for floating point numbers to fixed-point with six decimal places.
cout.setf(ios_base::fixed, ios_base::floatfield);
- The program prompts the user to enter the size of an array,
n , and creates a dynamic array arr of size n .
cout << "Please the size of array:";
int n = 0;
cin >> n;
double* arr = new double[n];
- The program then prompts the user to enter
n numbers, which are stored in the array arr .
for (int i = 0; i < n; i++) {
cout << "Please enter number" << i << ": ";
cin >> arr[i];
}
- The program calculates the sum of the numbers in the array and prints it out. It also calculates the average of the numbers and prints it out.
double sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
cout << "Sum: " << sum << endl;
cout << "Average: " << sum / n << endl;
- Finally, the program deallocates the memory allocated to the array
arr using the delete[] operator and returns 0, signaling successful execution of the program.
delete [] arr;
return 0;
This program demonstrates the use of dynamic memory allocation in C++, as well as basic input/output and arithmetic operations. |