0

列数が 2 であることがわかっている 3 次元整数配列を作成しようとしています。malloc を使用して配列を順次初期化しています。何が間違っているのか教えてください。

int **output_vertex[2];
for(int j=0;j<4;j++)
    output_vertex[j]= (int **)malloc(sizeof(int **));
output_vertex[1][0]==(int*)malloc(2*sizeof(int));
output_vertex[1][0][0] =11;
//also tried  *output_vertex[1][0] =11;
4

2 に答える 2

1

私はあなたのエラーが何であるか(またはあなたが参照しているエラー)を理解するのに少し問題があります。まず、なぜ静的に配列を作成してからmallocを使用しているのかわかりません。次に、forループを4回(0、1、2、3)繰り返している理由がわかりません。あなたの割り当てはこのようなものであるべきではありません:

int **output_vertex;
output_vertex = (int **)malloc(2*(sizeof(int **)));
于 2012-10-14T02:20:56.487 に答える
1

あなたが持っている配列宣言は、意図したものではありません。intへのポインターへのポインターの2要素配列があります。このページは、これらの宣言を読むための優れたガイドです。

個人的には、typedef を使用して、次のような複雑な型をゼロから構築することを好みます。

typedef int[2] element_type; // this is the 2-element array of ints
typedef element_type* inner_type; // this is the array of unknown size
typedef inner_type[5] outer_type; // this is the actual type we want to use

outer_type output_vertex; // we now have an array of 5 inner_type variables on the stack
// The output_vertex is *uninitialized* so we have to initialize each of its elements
for (int i=0; i < 5; ++i) {
    output_vertex[i] = new inner_type[SOME_SIZE];
}
// do stuff with output_vertex now that it's initialized
// then, to prevent memory leaks, delete the memory you allocated
for (int i=0; i < 5; ++i) {
    delete[] output_vertex[i];
}

単純化する方法はおそらくありますが、それが出発点です。

inner_typeを追加可能にしたい場合は、生の配列の代わりに使用することを強くお勧めします。std::vector未加工の配列を使用して行う簿記は非常に多いため、その例は示しません。ただし、多かれ少なかれ、次のようにしますstd::vector

typedef std::pair<int,int> element_type; // this is the 2-element array of ints as a pair
typedef std::vector<element_type> inner_type; // dynamic vector this time

inner_type output_vertex[5]; // we now have an array of 5 inner_type variables on the stack
// do stuff with output_vertex

std::vector動的に割り当てられた配列と同じくらい高速ですが、自分で簿記を行う必要はありません。また、ヒープ割り当てオブジェクトをそれほど多く管理する必要がないという利点もあります。

std::vector生の配列はコンテナー (例: )と互換性がないことに注意してください。そのため、std::pair代わりにここで使用します。

C++11 (またはブースト) を使用でき、標準コンテナーに収まる 3 つ以上の項目の固定サイズの配列が必要な場合は、std::array.

于 2012-10-14T16:39:00.760 に答える