C++根据‘输入’动态分配数组大小

参考:https://blog.csdn.net/weixin_43798960/article/details/109315614

 

https://zhidao.baidu.com/question/299076440.html

适用于:

程序在编译时不能确定数组长度,在运行时需要动态分配内存空间的数组。

visual studio2017版本定义变长数组,

 1 #include <iostream>
 2 using namespace std;
 3 int main() {
 4     int len;
 5     int num[len];
 6     for (int i = 0; i < len; i++) {
 7         int temp;
 8         cin >> temp;
 9         num[i] = temp;
10     }
11     system("pause");
12     return 0;
13 }

错误提示:

表达式必须含有常量,变量‘len’的值不可用作常量。

解决办法:

new开辟了一段内存空间后会返回这段内存的首地址,所以要把这个地址赋给一个指针,所以要用int *p=new int[len];

 1 #include <iostream>
 2 using namespace std;
 3 int main() {
 4     int len;
 5     //int num[len];
 6     int *num;
 7     num = new int[len];
 8 
 9     for (int i = 0; i < len; i++) {
10         int temp;
11         cin >> temp;
12         num[i] = temp;
13     }
14     system("pause");
15     return 0;
16 }

 

posted @ 2021-11-05 19:02  花知  阅读(604)  评论(0)    收藏  举报