数组是编程中,一种重要的数据类型,灵活的掌握就显得尤为的重要,今天我也遇上了这么个问题,就做一些总结,是对数组大小的问题:
在声明数组类型的时候,是要规定它的大小的,这就存在常量和变量的使用。
代码如下:显示了相应的使用方法
#include <IOSTREAM>
using namespace std;
#define BOY 5
void main(){
//定义数组时,大小必须确定, 如下要么const,要么宏定义
const int n=3;
int baby[n];
for(int i=0;i<n;i++)
{
cin>>baby[i];
}
for(int j=0;j<n;j++)
{
cout<<baby[j]<<" ";
}
cout<<endl;
cout<<"anthor ways !!!"<<endl;
// 通过宏定义
int Oky[BOY];
for(int x=0;x<BOY;x++)
{
cin>>Oky[x];
}
for(int y=0;y<BOY;y++)
{
cout<<Oky[y]<<" ";
}
cout<<endl;
//一位数组,大小为变量
cout<<"if it is changeable ???"<<endl;
int ca;
cin>>ca;
int *cable=new int[ca];
for(int xy=0;xy<ca;xy++)
{
cin>>cable[xy];
}
for(int yx=0;yx<ca;yx++)
{
cout<<cable[yx]<<" ";
}
cout<<endl;
//如果二维数组,有两个变量,如何赋值呢
cout<<"next is two change able !"<<endl;
int a,b;
cin>>a;
cin>>b;
//为什么数字读不进去呢???,我去下面的语句居然用了我两个多g的内存
int **tt=new int *[a];
// cout<<"what ???"<<endl;
for(i=0;i<a;++i) tt[i]=new int[b]; //在一个循环体中定义的变量也是全局的
// cout<<"what ???"<<endl;
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
// cout<<"what ???"<<endl;
cin>>tt[i][j];
}
cout<<endl;
}
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
cout<<tt[i][j];
}
cout<<endl;
}
cout<<"suprise !!!"<<endl;
}
如果还有其他问题,在做扩充吧。