所以我一直在尝试获取数组大小的输入,然后将其元素显示在屏幕上,但是当我放置时 数组的大小:7 数组的元素:1 2 3 4 5 6 7 输出是:
1
2
3
4
5
6
6
代码:
#include <iostream>
using namespace std;
int main () {
int n , Arr[n];
cout << "please put the size of the array " ;
cin >> n;
cout << "please enter array's elemets ";
for (int k=0; k<n ; k++) {
cin >> Arr[k];
}
for (int i=0;i<n;i++){
cout << Arr[i] << endl;
}
}
答案 0 :(得分:5)
int Arr[n]
其中n
不是编译时常量是非法的C ++代码。一些编译器允许它作为扩展(可变长度数组)。
即使使用VLA扩展名,代码也无效,因为在您的代码中使用时n
未初始化。
首先是真正的解决方案:
使用std::vector
(tadaaa):
#include <iostream>
#include <vector>
int main () {
int n;
std::vector<int> arr;
std::cout << "please put the size of the array " ;
std::cin >> n;
arr.reserve(n); // optional
std::cout << "please enter array's elemets ";
for (int k=0; k<n ; k++) {
int elem;
std::cin >> elem;
arr.push_back(elem);
}
for (auto e : arr) {
std::cout << e << std::endl;
}
}
如果你需要针对C ++ 98编译(哇):
for (std::vector<int>::iterator it = arr.begin(); it != arr.end(); ++it) {
std::cout << *it << std::endl;
}
或只是:
for (std::size_t i = 0; i < arr.size(); ++i) {
std::cout << arr[i] << std::endl;
}
如果您坚持使用VLA(我建议不要使用VLA):
int n;
cout << "please put the size of the array " ;
cin >> n;
int Arr[n];
cout << "please enter array's elemets ";
for (int k=0; k<n ; k++) {
cin >> Arr[k];
}
for (int i=0;i<n;i++){
cout << Arr[i] << endl;
}
答案 1 :(得分:0)
正如许多其他人在评论部分提到的那样,另一种方式(如果你想坚持使用C数组)将是在堆上动态分配数组。
S:
答案 2 :(得分:0)
来自dcl.init#12:
如果没有为对象指定初始化程序,则该对象为 默认初始化。使用自动或自动存储对象时 获得动态存储持续时间,该对象具有不确定性 值,如果没有为对象执行初始化,那么 对象保留不确定的值,直到替换该值 ([expr.ass])。
unsigned char c;
unsigned char d = c; // OK, d has an indeterminate value
int e = d; // undefined behavior
因此,在您的代码中:
int n , Arr[n];
n
具有不确定的值,直到在cin >> n;
中分配
使用具有此不确定值的n
(不是value- / zero- / default-initialized且未分配),可能导致未定义的行为。