【C++总结】数组

来源:互联网 发布:脚本级网络游戏编程 编辑:程序博客网 时间:2024/05/21 14:08

数组的初始化

数组定义的时候就要确定大小

 int arr1[10];//定义一个10个元素的数组 int arr2[10] = {1, 2, 3, 4}; int arr22[20]{1,2,3,4}; int arr3[] = {1, 2, 3, 4}; int arr33[]{1,2,3,4,5}; int n; int arr[n];//错误的初始化,n只能是常量,不能是变量

创建动态数组

平常的数组的限制

  1. 数组的长度固定不变
  2. 编译时必须知道其长度
  3. 数组只能定义在块语句内存在
    动态数组存在=堆中
 int n; cin >> n; int *p = new int[n];//n不确定 int *p = new int[10];

动态数组的使用

   int *p = new int[n]();    p[0] = 1;    p[1] = 2;    p[2] = 3;    cout << p[0] << endl;     cout << p[1] << endl;    //遍历动态数组    for(int * q = p; q != p + n; q++) {        cout << *q <<endl;    } delete []p;//删除,回收内存
0 0
原创粉丝点击