注册 登录
编程论坛 C++教室

怎样动态申请n维数组?

wangweicoin 发布于 2007-09-08 14:54, 1471 次点击

请问怎么动态申请2维数组,n维呢? 我查过书,看不太懂,是不是只有一组下标才能用变量表达式?


float (*cp)[25][10];
cp=new float[10][25][10];

这样申请是什么意思呢?
6 回复
#2
wlmau2007-09-08 15:49
第一个语句意思比较明显,如果指针不加括号则是申请了[25][10]个指针了,加了则表示申请了一个指针指向二维数组;第二条语句是说申请了10个二维数组空间,cp指向第一个的下标.
我是这么理解的
#3
wangweicoin2007-09-08 16:05

回2楼:
对,应该是这个意思,谢谢。但是好像如果要使用变量表达式最多也就是改成 cp=new float[N][25][10]; 依然像是不能用变量表达式指定2维数组的大小。 因为是动态的嘛,我想把2维数组中的下标表达式都用变量表达式表示,可以吗?

#4
HJin2007-09-08 17:20
回复:(wangweicoin)怎样动态申请n维数组?

/**
d1 can be a variable, d2---dn have to be constants.
The reason is that the complier needs to know how much
memory should be allocated.
*/
int d1;
const int d2=5;
...
const int dn=5;

float (*cp)[d2]...[dn];

d1=3;
cp = new float[d1][d2]...[dn];

delete [] cp;

d1=7;
cp = new float[d1][d2]...[dn];

delete [] cp;

#5
wangweicoin2007-09-08 19:07
哦,原来是这样啊,谢谢!那这样动态申请多维数组有什么好处呢?感觉就是申请了d1个n-1维空间,要是我想要用户自己输入2维数组空间的大小,就像是动态申请一个普通数组那样,能不能做到呢?
#6
hegj2007-09-08 22:00

我也是新手,看书有这么一个;

typedef int* IntArrayPtr;

int d1,d2;
cout<<"Enter the row and column dimensions of the array:\n";
cin>>d1>>d2;
IntArrayPtr *m=new IntArrayPtr[d1];
int i,j;
for(i=0;i<d1;i++)
m[i]=new int[d2];
//m现在就变成了的d1行d2列的二维数组。

#7
wangweicoin2007-09-08 22:11
还真是啊,有意思! 谢谢!
1