【考点 · 6级】 new/delete 是 C++ 动态内存管理运算符,属于「指针与内存」类考点。
【说人话】 栈上的变量编译期就定好了大小,而 new 能在堆(heap)上按需分配内存,返回一个指向该内存的指针。用完必须用 delete 释放,否则内存泄漏。数组要用 new[] 和 delete[] 配对,否则行为未定义。
new int → 分配 1 个 int,返回 int*new int[10] → 分配 10 个 int 的数组,返回 int*delete p → 释放单个对象delete[] p → 释放数组nullptr
# 输出:42 → 0 10 20 30 40
static_cast<double> 做浮点除法。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int n;
cin >> n; // 读取数组大小
int* arr = new int[n]; // 堆上分配 n 个 int
double sum = 0;
for (int i = 0; i < n; i++) {
cin >> arr[i]; // 读入每个元素
sum += arr[i]; // 累加求和
}
cout << fixed << setprecision(2);
cout << "平均值: " << sum / n << endl;
delete[] arr; // 释放数组内存
arr = nullptr;
cout << "Memory freed" << endl;
return 0;
}