求助:c 二维数组怎么动态分配!!

开发编程  |  电脑网络

分享:
2014-10-31

2014-10-31最佳答案


给你个例子#include<iostream>using namespace std;class test{public:test(int a[][3],int m,int n);~test();void print();private:int** array;int num1,num2;};test::test(int a[][3],int m,int n){num1=m;num2=n;array=new int *[num1];for (int i=0;i<num1;i++){array[i]=new int[num2];}for (i=0;i<num1;i++){for(int j=0;j<num2;j++){array[i][j]=a[i][j];}}}test::~test(){for (int i=0;i<num1;i++){delete[] array[i];}delete[] array;}void test::print() {for (int i=0;i<num1;i++){for (int j=0;j<num2;j++){cout<<array[i][j]<<" ";}cout<<endl;}}void main(){int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};cout<<a<<endl;;test t1(a,3,3);t1.print();}

其它1条答案


#include<stdio.h>#include<stdlib.h>void main(){int n,m;int i,j;scanf("%d %d",&n,&m);int **a,**b;a=(int**)malloc(n*sizeof(int*));for(i=0;i<n;i++){ a[i]=(int*)malloc(m*sizeof(int));}b=(int**)malloc(m*sizeof(int*));for(i=0;i<n;i++){ b[i]=(int*)malloc(n*sizeof(int));}for(i=0;i<n;i++){for(j=0;j<m;j++){scanf("%d",*(a+i)+j);}}for(i=0;i<n;i++){for(j=0;j<m;j++){b[j][i]=a[i][j];}}for(i=0;i<m;i++){for(j=0;j<n;j++){printf("%d",*(*(b+i)+j));if(j==n-1)printf("\n");elseprintf(" ");}}}

2014-10-31