C++中如何動態(tài)分配二維數(shù)組
一、問題的提出
//////////////////////////////////////////////////////
#include <iostream.h>
const int M=200;
void main()
{
double a[M][M], b[M][M];
double aa=0, bb=0;
for(int i=0; i<M; i++)
for(int j=0; j<M; j++)
{
a[i][j]=1.0;
b[i][j]=1.0;
aa+=a[i][j];
bb+=b[i][j];
}
cout<<"aa="<<aa<<", bb="<<bb<<endl;
}
////////////////////////////////////////////////////////
M=200,運行很正常,可以輸出結(jié)果。當(dāng)M=300時就會出現(xiàn)運行錯誤。
是不是C++中對數(shù)組大小有限制,怎么申請大數(shù)組呢?
高人指點:
你這種方法建的數(shù)組好象是存在STACK里, 大小有限制.
2維數(shù)組在C/C++里不是很好用.建議用一維數(shù)組代替, 可以用 NEW 建指針數(shù)組, 這樣可以用大數(shù)組.
其實最好用VECTOR, 做動態(tài)時很方便, 而且從2維到3維也更自然一些
二、問題的解決
A.用一維數(shù)組代替,應(yīng)用new、delete命令。
//////////////////////////////////////////////////////
#include <iostream.h>
const int M=500;
void main()
{
double *a, *b;
double aa=0, bb=0;
a=new double[M*M];
b=new double[M*M];
for(int i=0; i<M; i++)
for(int j=0; j<M; j++)
{
a[i+j*M]=1.0;
b[i+j*M]=1.0;
aa+=a[i+j*M];
bb+=b[i+j*M];
}
cout<<"aa="<<aa<<", bb="<<bb<<endl;
delete []a;
delete []b;
}
///////////////////////////////////////////////////////
OK,用NEW建指針數(shù)組,運行通過,M=1000都沒問題, :)
B.用vector命令。
////////////////////////////////////////////////////////
#include <iostream.h>
#include <vector>
using std::vector;
const int M=1000;
void main()
{
vector <double> a(M*M);
vector <double> b(M*M);
double aa=0, bb=0;
for(int i=0; i<M; i++)
for(int j=0; j<M; j++)
{
a[i+j*M]=1.0;
b[i+j*M]=1.0;
aa+=a[i+j*M];
bb+=b[i+j*M];
}
cout<<"aa="<<aa<<", bb="<<bb<<endl;
}
////////////////////////////////////////////////////////////////
OK,好像也可以,不錯不錯。
C.網(wǎng)上找到個比較好的。
http://nothingnowhere.blogchina.com/4539351.html
c++中如何動態(tài)分配二維數(shù)組
關(guān)鍵詞: 二維數(shù)組
#include<iostream.h>
void main()
{
int **p;
int N,M,s=0;
cin>>N>>M;
p = new int*[N];
for(int i=0;i<N;i++) { p[i] = new int[M]; }
for(int j=0;j<M;j++)
for(int k=0;k<N;k++)
{p[k][j]=s++; cout<<p[k][j]<<endl;}
}
/////////////////////////////////////////////////
這個方法確實不錯,用起來更方便。
posted on 2007-07-17 13:24 東東會會 閱讀(4313) 評論(2) 編輯 收藏 引用 所屬分類: C++ 基礎(chǔ)