題目:
二維數(shù)組是數(shù)組的數(shù)組,而數(shù)組可以通過指針動態(tài)創(chuàng)建。如果動態(tài)創(chuàng)建的數(shù)組元素也是指針,數(shù)組中的每個元素就都可以存儲數(shù)組的地址。使用這個概念,創(chuàng)建一個數(shù)組,其中包含三個數(shù)組指針,每個數(shù)組都可以包含六個int類型的值。把第一個整數(shù)數(shù)組的值設(shè)置為1到6,下一個數(shù)組的元素值設(shè)置為第一個數(shù)組元素的平方,第三個數(shù)組的元素值設(shè)置為第一個整數(shù)數(shù)組元素的立方。輸出這三個數(shù)組的內(nèi)容,再釋放已分配的內(nèi)存。
答案:
#include <iostream>
#include <iomanip>
#include <cmath>
using std::cout;
using std::endl;
using std::cin;
using std::setw;
void main() {
const int arrays = 3;
const int elements = 6;
int** ppint = new int*[arrays];
int i=0, j=0;
for (i = 0; i < arrays; i++) {
ppint[i] = new int[elements]; // 等價于 *(ppint + i) = new int[elements];
for (j = 0; j < elements; j++) {
ppint[i][j] = pow((j+1), (i+1)); // 等價于 *(*(ppint + i) + j) = pow((j+1), (i+1));
}
}
for (i = 0; i < arrays; i++) {
for (j = 0; j < elements; j++) {
cout << setw(4) << *(*(ppint + i) + j);
}
cout << endl;
}
for (i = 0; i < arrays; i++)
delete [] *(ppint + i);
delete [] ppint;
}
輸出結(jié)果:
1 2 3 4 5 6
1 4 9 16 25 36
1 8 27 64 125 216