用C++编程实现:动态一维数组a(100)、动态二维数组b(20×25)、动态三维数组c(9×8×5)、动态二维数组d(m×n,m和n由键盘输入,可以输入25和20)的申请和释放,将数组元素的值赋值为下标的组合:a[i]=i; b[i][j]=i*25+j; c[i][j][k] =i*100+j*10+k,d[i][j]=i*n+j; 并求每个数组的元素之和。
时间: 2023-05-10 21:56:14 浏览: 141
c++动态数组申请(包括一维,二维的)
以下是用C++编程实现动态数组的申请和释放,以及将数组元素的值赋值为下标的组合,并求每个数组的元素之和的代码:
```c++
#include <iostream>
using namespace std;
int main() {
// 动态一维数组a(100)
int *a = new int[100];
int sum_a = 0;
for (int i = 0; i < 100; i++) {
a[i] = i;
sum_a += a[i];
}
cout << "sum_a = " << sum_a << endl;
delete[] a;
// 动态二维数组b(20×25)
int **b = new int*[20];
int sum_b = 0;
for (int i = 0; i < 20; i++) {
b[i] = new int[25];
for (int j = 0; j < 25; j++) {
b[i][j] = i * 25 + j;
sum_b += b[i][j];
}
}
cout << "sum_b = " << sum_b << endl;
for (int i = 0; i < 20; i++) {
delete[] b[i];
}
delete[] b;
// 动态三维数组c(9×8×5)
int ***c = new int**[9];
int sum_c = 0;
for (int i = 0; i < 9; i++) {
c[i] = new int*[8];
for (int j = 0; j < 8; j++) {
c[i][j] = new int[5];
for (int k = 0; k < 5; k++) {
c[i][j][k] = i * 100 + j * 10 + k;
sum_c += c[i][j][k];
}
}
}
cout << "sum_c = " << sum_c << endl;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 8; j++) {
delete[] c[i][j];
}
delete[] c[i];
}
delete[] c;
// 动态二维数组d(m×n,m和n由键盘输入,可以输入25和20)
int m, n;
cout << "Please input m and n: ";
cin >> m >> n;
int **d = new int*[m];
int sum_d = 0;
for (int i = 0; i < m; i++) {
d[i] = new int[n];
for (int j = 0; j < n; j++) {
d[i][j] = i * n + j;
sum_d += d[i][j];
}
}
cout << "sum_d = " << sum_d << endl;
for (int i = 0; i < m; i++) {
delete[] d[i];
}
delete[] d;
return 0;
}
```
注意:以上代码中的申请和释放动态数组的方式是使用new和delete,也可以使用malloc和free,但是要注意对应的数据类型和释放方式。
阅读全文