の配列に実行時メモリを割り当てる方法はsize[4][3]
?
すなわちint a[4][3]
2D 配列または 3D 配列にメモリを割り当てる方法よりも、実行時にメモリを配列に割り当てる必要がある場合。
コメントに基づいて回答を編集します。次元ごとに個別に割り当てます。2D 配列の場合、2 レベルの割り当てが必要です。
*a = (int**)malloc(numberOfRows*sizeof(int*));
for(int i=0; i<numberOfRows; i++)
{
(*arr)[i] = (int*)malloc(numberOfColumns*sizeof(int));
}
純粋な C のアプローチは次のとおりです。
int (*size)[4][3];
size = malloc(sizeof *size);
/* Verify size is not NULL */
/* Example of access */
(*size)[1][2] = 89;
/* Do something useful */
/* Deallocate */
free(size);
利点は、中間ポインターを割り当てないことで消費するメモリが少なくなり、メモリの単一ブロックを処理し、割り当て解除がより簡単になることです。これは、2 つ以上の次元を持ち始める場合に特に重要です。
欠点は、インデックスを作成する前にポインターを逆参照する必要があるため、アクセス構文がより複雑になることです。
callocを使用してください。これでうまくいくと思います。
int **p;
p=(int**)calloc(4,sizeof(int));
これはテンプレート化されたコンテナーであるため、使用できますstd::vector<>
(つまり、配列要素は必要な任意の型にすることができます)。std::vector<>
動的なメモリ使用が可能です (必要に応じて vector<> のサイズを変更できます..メモリは自動的に割り当てられ解放されます)。
例えば:
#include <iostream>
#include <vector>
using namespace std; // saves you from having to write std:: in front of everthing
int main()
{
vector<int> vA;
vA.resize(4*3); // allocate memory for 12 elements
// Or, if you prefer working with arrays of arrays (vectors of vectors)
vector<vector<int> > vB;
vB.resize(4);
for (int i = 0; i < vB.size(); ++i)
vB[i].resize(3);
// Now you can access the elements the same as you would for an array
cout << "The last element is " << vB[3][2] << endl;
}