如何在接收变量值作为输入的同时使用变量声明数组?检查我的代码

问题描述

int a;
cin>>a;
int arr[a];

我想根据用户的大小声明一个数组。我是编程新手。 可以做什么?这个方法对吗?

解决方法

你想要实现的东西叫做可变长度数组,简称 VLA which isn't a part of C++ standard

可以做什么?

它调用一个 undefined behavior

这个方法正确吗?

没有。在这里获得 std::vector<> 一点帮助的最佳机会。它动态分配请求的数据字节,您可以选择使用所需的值初始化它们。

你可以这样实现:

int n = 0;
std::cin >> n; // make sure it's a valid size
std::vector<int> a(n);

如果您希望它的运行时间保持增长,只需​​使用其 push_back() 方法,您就可以通过其 size() 获得矢量大小。

,

您已经标记了这个 C++,在这种情况下,很少有借口不使用 std::vector 解决这个问题。

如果你必须这样做,你可以写成 C 风格:

for (int i = 1; i <= 9; i++) {
System.out.print(i + " | ");
for (int j = 1; j <= 9; j++) {
// Display the product and align properly
System.out.printf("%4d",i * j);
}
System.out.println(); // This is the print statement I'm referring to. How can I visualize this?
}

或更好(根据 Thomas 在下面的评论):

int a;
cin >> a;
int * arr = (int *)malloc(sizeof(int) * a);

但矢量绝对是首选。