You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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;
}

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:00:45