VS2017中C++用用户输入值定义数组报错的解决请求
Hey there! The error you're seeing happens because variable-length arrays (VLAs)—like int a[n] where n is a runtime input—aren't part of standard C++. Some compilers (like GCC) allow them as an extension, but Visual Studio's C++ compiler doesn't support this feature, hence the "expression must have a constant value" message.
You mentioned trying new or pointers but didn't get it right—let's fix that with clear examples, plus a better alternative using standard library containers.
Original Problem Code
int n; cout << "Enter n:" ; cin >> n; int a[n]; // Error here in VS 2017
Solution 1: Dynamic Allocation with new and delete
You can manually allocate memory on the heap using new[], which works with runtime values. Just remember to free the memory with delete[] when you're done to avoid memory leaks:
#include <iostream> using namespace std; int main() { int n; cout << "Enter n:" ; cin >> n; // Dynamically allocate array int* a = new int[n]; // Example: Use the array to store and print values for (int i = 0; i < n; ++i) { a[i] = i * 2; cout << a[i] << " "; } // Critical: Free the allocated memory to prevent leaks delete[] a; return 0; }
Solution 2: Use std::vector (Recommended)
The best practice in C++ is to use std::vector from the standard library. It handles dynamic memory automatically, so you don't have to worry about forgetting to delete memory, and it's fully compatible with all standard-compliant compilers including VS 2017:
#include <iostream> #include <vector> // Don't forget this required header! using namespace std; int main() { int n; cout << "Enter n:" ; cin >> n; // Create a vector of size n, elements initialized to 0 by default vector<int> a(n); // Use the vector just like a regular array for (int i = 0; i < n; ++i) { a[i] = i + 1; cout << a[i] << " "; } // No manual cleanup needed—vector handles memory release automatically return 0; }
This approach is safer, more readable, and aligns with modern C++ practices.
Content of the question originates from Stack Exchange, question author Ariya Sebty

