Bluec Z
Bluec Z

Reputation: 1

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

Upvotes: 0

Views: 132

Answers (3)

Ranjeeth Mahankali
Ranjeeth Mahankali

Reputation: 390

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.

Upvotes: 0

Adrian Mole
Adrian Mole

Reputation: 51825

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

Upvotes: 2

R Sahu
R Sahu

Reputation: 206577

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

Upvotes: 2

Related Questions