简体   繁体   中英

how to fix this code for giving me "expression did not evaluate to a constant"

I tried to write this code but it says expression did not evaluate to a constant. I learn that this is because VS does not allow an undeclared array, as "n" is not understood by VS. How can i fix this code with a declared array?

#include<iostream>
using namespace std;


int main()
{

    int i, n;
    cout << "Enter size of array:";
    cin >> n;
    int a[n];
    cout << "Enter elements of array:" << endl;

    for (i = 0; i < n; i++)
        cin >> a[(i + n - 1) % n];

    cout << "Result after left shift:" << endl;
    for (i = 0; i < n; i++)
        cout << a[i] << " ";
    cout << endl;


    return 0;
}

How can i fix this code with a declared array?

Option 1

Declare the array with sufficiently large size and make sure that n is less than or equal to the size before using the array.

 int i, n;
 int a[1000];
 cout << "Enter size of array (less than or equal to 1000):";
 cin >> n;
 if ( n > 1000 )
 {
    // Deal with the problem.
 }
 else
 {
    // Use the array.
 }

Option 2

Use std::vector .

 int i, n;
 cout << "Enter size of array:";
 cin >> n;
 std::vector<int> a(n);

Variable length arrays (VLAs) are not part of the C++ language, although some compilers (like g++) support them as an extension.

You should be using the std::vector container from the Standard Template Library , instead. Once declared and properly initialized, a std::vector can be used much like a plain array:

#include<iostream>
#include <vector>
using std::cout; using std::cin; using std::endl;

int main()
{
    int i, n;
    cout << "Enter size of array:";
    cin >> n;
    std::vector<int> a(n);
    cout << "Enter elements of array:" << endl;

    for (i = 0; i < n; i++)
        cin >> a[(i + n - 1) % n];

    cout << "Result after left shift:" << endl;
    for (i = 0; i < n; i++)
        cout << a[i] << " ";
    cout << endl;


    return 0;
}

You have to allocate the array on the heap like this:

int* a = new int[n];

But when you do heap allocations, always remember to delete the allocated memory after you are done using it:

delete[] a;

If you don't want to worry about deleting the memory, you can look into std::vector .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM