给出动态建立和删除二维数组的函数,方便大家使用:
/*建立时 先给行分配*[rows]内存空间,再给每行分配int [cols]内存空间;删除时,过程刚好相反*/
#include <except.h>
template <class T>
bool Make2DArray(T ** &x, int rows, int cols)
{// Create a two dimensional array.
try {
// create pointers for the rows
x = new T * [rows];
// get memory for each row
for (int i = 0; i < rows; i++)
x[i] = new int [cols];
return true;
}
catch (xalloc) {return false;}
}
template <class T>
void Delete2DArray(T ** &x, int rows)
{// Delete the two-dimensional array x.
// delete the memory for each row
for (int i = 0; i < rows; i++)
delete [] x[i];
// delete the row pointers
delete [] x;
x = 0;
}
1.C语言动态建立二维数组的示例:
#include <string>
#include <stdio.h>
#include <stdlib.h>
void TestArray(int **p,int rows,int cols)
{
int i=0;
int j=0;
for(i = 0; i < rows; i++)
for( j = 0; j < cols; j++)
printf("%d", p[i][j]);
}
void main()
{
int i=0;
int j=0;
int rows=5;
int cols=5;
int **a = (int**)malloc(sizeof(int*) * rows);
for(i = 0; i < rows; i++)
{
a[i] = (int*)malloc(sizeof(int) *cols);
if(a[i])
{
for( j = 0; j < cols; j++)
a[i][j]=1;
}
}
TestArray(a,rows,cols);
printf("/n");
///释放内存//
free(a);
}
2.C++动态建立二维数组的示例:
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>
#include <map>
#include <string>
//#include <stdio.h>
//#include <stdlib.h>
#include <fstream>
#include <iomanip>
#define Type int
using namespace std;
Type **getmemory(int m,int n);
int main()
{
//C++读文件的数据
ifstream inFile("test.txt");
if(!inFile.is_open())
{
cout<<"未知错误,文件未打开"<<endl;
system("pause");
return 1;
}
char aLine[10];
char ch;
while(!inFile.eof())
{
inFile>>aLine[i].c>>;
cout<<setw(6)<<aLine[i]<<endl;
}
inFile.close();
system("pause");
int i,j;
const int n = 10;
const int m = 41;
Type** arrayname = new Type*[m];
for ( i = 0;i < n;i ++)
arrayname[i] = new Type [m];
for ( i = 0;i < n;i ++)
for ( j = 0;j < m;j ++)
arrayname[i][j] = -1;
Type **test = getmemory(m,n);;
for ( i = 0;i < n;i ++)
for ( j = 0;j < m;j ++)
test[i][j] = -1;
for ( i = 0;i < n;i ++)
{
for ( j = 0;j < m;j ++)
cout << test[i][j];
cout << endl;
}
return 0;
}
Type **getmemory(int m,int n) //得到一个[m][n]的动态数组
{
Type **ptr=new Type*[m];
for (int index=0;index<m;++index)
{
ptr[index] = new Type[n];
}
return ptr;
}