C++动态数组

C++线程中经常会用到数组,在《C++程序设计第2版--谭浩强》中,还明确指出,定义数组时长度必须用常量表达式。

不过,这两天由于在开发一个C++工具,忽然发现,C++定义一维数组时,也可以用变量来定义长度了。

    int s=0;  //代表房间数量
    cout<<"Please input the number of rooms:";
    cin>>s;
    int robotNum=0;  //代表机器人数量
    cout<<"Please input the number of robots:";
    cin>>robotNum;
    int h=0;  //代表冲突标识的数量
    cout<<"Please input the number of conflict markings:";
    cin>>h;
    int m=robotNum*s;
    CTree tr[robotNum];

部分开发代码,最后一行正常运行。

不过用的较多的还是动态数组啦,因为项目中有很多结构体,结构体里面又有数组,数组的长度也不确定的情况下,这里面的数组就用动态开辟的方法了。

typedef struct CTNode{
    int *M;
    int preT; //进入该结点的变迁的编号
    CTNode *firstChild;
    CTNode *nextSibling;
    CTNode *parent;
}CTNode,*CTree;

定义指针M的目的就是为了动态地创建数组。

CTree c=new CTNode;
c->M=new int[s];

s就可以是任意变量了。

而对于二维数组,举个例子,创建矩阵out和in。

       int **out,**in;
       out=new int*[t];
       in=new int*[t];
       for(int f=0;f<t;f++){
            out[f]=new int[s];
            in[f]=new int[s];
       }

这样就可以动态开辟空间,不用为长度不确定而烦恼了。

 

转载于:https://www.cnblogs.com/qiuhaojie/p/5835510.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值