其实就是如何动态开辟二维空间的问题, 这个问题在C++ 学习者中是每个人都会遇到的, 针对这个问题我写了一个 Demo code, 希望对你以及对大家会有一些帮助。
[CODE]
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int rows = 2;
int cols = 3;
// create a dynamic array
int ** array = NULL;
array = new int * [rows];
for(int i = 0; i < rows; i++)
{
array[i] = new int[cols];
// init this 2d array
for(int j = 0; j<cols; j++)
{
array[i][j] = (i+1)*(j+1);
}
}
// to check what we have done
for(int i = 0; i < rows; i++)
{
for(int j = 0; j<cols; j++)
{
cout<<array[i][j]<<" ";
}
cout<<endl;
}
// before you leave the program
// you should release the space what you have dynamically allocated
// to delete the allocation
for(int i = 0; i<rows; i++)
{
delete [] array[i];
array[i] = NULL; // to avoid wild pointer
}
delete [] array;
array = NULL; // to avoid wild pointer
system("pause");
return 0;
}
[CODE]
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int rows = 2;
int cols = 3;
// create a dynamic array
int ** array = NULL;
array = new int * [rows];
for(int i = 0; i < rows; i++)
{
array[i] = new int[cols];
// init this 2d array
for(int j = 0; j<cols; j++)
{
array[i][j] = (i+1)*(j+1);
}
}
// to check what we have done
for(int i = 0; i < rows; i++)
{
for(int j = 0; j<cols; j++)
{
cout<<array[i][j]<<" ";
}
cout<<endl;
}
// before you leave the program
// you should release the space what you have dynamically allocated
// to delete the allocation
for(int i = 0; i<rows; i++)
{
delete [] array[i];
array[i] = NULL; // to avoid wild pointer
}
delete [] array;
array = NULL; // to avoid wild pointer
system("pause");
return 0;
}
[/CODE]