C++中如何根据用户输入创建数组?是否改用vector?
Hey there! Let's break down what's going on with your array code and find the right way to handle dynamic-sized collections in C++.
为什么你的代码报错,朋友的却能运行?
First off, let's talk about variable-length arrays (VLAs)—arrays where the size is set at runtime (like your friend's int px[num] where num comes from user input).
- The C++ standard does NOT support VLAs—they're a non-standard extension that compilers like GCC happen to allow as a bonus feature. Your friend's code works because their compiler enables this extension, but if you tried it on a different compiler (like MSVC), it would fail just like your code did.
- Your code uses
const int t, but since you're assigning it a value fromcinat runtime, it's a runtime constant, not a compile-time constant. C++ requires fixed array sizes to be known when the code is compiled, so this is why your code throws an error.
正确的解决方案:用std::vector
Forget about VLAs— the standard, portable, and safe way to create a dynamic-size array in C++ is to use std::vector. It's built exactly for this scenario:
- It handles dynamic resizing automatically
- Manages memory for you (no manual cleanup or leaks to worry about)
- Works across all standard-compliant compilers
Here's how you'd rewrite your code with vector:
#include <iostream> #include <vector> // Don't forget to include this header! int main() { int t; std::cin >> t; // Create a vector of doubles with size t, all initialized to 0.0 std::vector<double> myarray(t, 0.0); // Use it just like a regular array: myarray[2] = 9.8; std::cout << myarray[2] << std::endl; return 0; }
要不要用string?
Short answer: No. std::string is specifically designed for handling character sequences (text). It's not meant to store arbitrary types like double, so it's not a suitable replacement here.
总结
- Avoid VLAs even if they work on your friend's compiler—they're non-standard and can break when you switch compilers or environments.
- Stick with
std::vectorfor dynamic arrays in C++—it's the idiomatic, safe, and portable choice.
内容的提问来源于stack exchange,提问作者Www

