admin 发表于 2024-1-11 22:36:57

如何创建一个动态数组

```
#include <iostream>

/**
* @briefThis 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;
    for (int i = 0; i < n; i++) {
      cout << "Please enter number" << i << ": ";
      cin >> arr;
    }
    double sum = 0;
    for (int i = 0; i < n; i++) {
      sum += arr;
    }
    cout << "Sum: " << sum << endl;
    cout << "Average: " << sum / n << endl;
    delete [] arr;
    return 0;
}
```

---



The [`main.cpp`](command:_github.copilot.openRelativePath?%5B%22main.cpp%22%5D "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:

1. The `main` function starts by declaring a pointer `pNumber` and allocating memory for an integer using the `new` operator.

```cpp
int* pNumber = new int;
```

2. Another pointer `pNumber2` is declared and assigned the same memory address as `pNumber`.

```cpp
int * pNumber2 = pNumber;
```

3. 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;`.

```cpp
delete pNumber2;
```

4. The program then sets the output format for floating point numbers to fixed-point with six decimal places.

```cpp
cout.setf(ios_base::fixed, ios_base::floatfield);
```

5. The program prompts the user to enter the size of an array, `n`, and creates a dynamic array `arr` of size `n`.

```cpp
cout << "Please the size of array:";
int n = 0;
cin >> n;
double* arr = new double;
```

6. The program then prompts the user to enter `n` numbers, which are stored in the array `arr`.

```cpp
for (int i = 0; i < n; i++) {
    cout << "Please enter number" << i << ": ";
    cin >> arr;
}
```

7. 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.

```cpp
double sum = 0;
for (int i = 0; i < n; i++) {
    sum += arr;
}
cout << "Sum: " << sum << endl;
cout << "Average: " << sum / n << endl;
```

8. Finally, the program deallocates the memory allocated to the array `arr` using the `delete[]` operator and returns 0, signaling successful execution of the program.

```cpp
delete [] arr;
return 0;
```

This program demonstrates the use of dynamic memory allocation in C++, as well as basic input/output and arithmetic operations.
页: [1]
查看完整版本: 如何创建一个动态数组