动态创建和删除二维数组

 

给出动态建立和删除二维数组的函数,方便大家使用:

/*建立时 先给行分配*[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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值