を使用して多次元配列を割り当てるときはnew
、次のようにしています。
void manipulateArray(unsigned nrows, unsigned ncols[])
{
typedef Fred* FredPtr;
FredPtr* matrix = new FredPtr[nrows];
for (unsigned i = 0; i < nrows; ++i)
matrix[i] = new Fred[ ncols[i] ];
}
wherencols[]
には、 の各要素の長さmatrix
とnrows
の要素の数が含まれmatrix
ます。
にデータを入力したい場合はmatrix
、
for (unsigned i = 0; i < nrows; ++i) {
for (unsigned j = 0; j < ncols[i]; ++j) {
someFunction( matrix[i][j] );
しかし、私は非常に注意するように言っているC++ FAQを読んでいます。各行をNULL
最初に初期化する必要があります。次に、trycatch
行の割り当てを行う必要があります。なぜこれがすべてなのか、私には本当にわかりません。私は常に(最初はそうですが)上記のコードでCスタイルで初期化しています。
FAQ こうしてほしい
void manipulateArray(unsigned nrows, unsigned ncols[])
{
typedef Fred* FredPtr;
FredPtr* matrix = new FredPtr[nrows];
for (unsigned i = 0; i < nrows; ++i)
matrix[i] = NULL;
try {
for (unsigned i = 0; i < nrows; ++i)
matrix[i] = new Fred[ ncols[i] ];
for (unsigned i = 0; i < nrows; ++i) {
for (unsigned j = 0; j < ncols[i]; ++j) {
someFunction( matrix[i][j] );
}
}
}
catch (...) {
for (unsigned i = nrows; i > 0; --i)
delete[] matrix[i-1];
delete[] matrix;
throw; // Re-throw the current exception
}
}
1/ 常に慎重に初期化するのは、とてつもないことですか、それとも非常に適切ですか?
2/非組み込み型を扱っているため、このように進めていますか? コードは (同じレベルの注意を払って) と同じdouble* matrix = new double[nrows];
でしょうか?
ありがとう
編集
回答の一部はFAQ の次の項目にあります