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