Question about a code

Hello guys! I have a question (which may be kind of not serious. Why exactly my visual studio compiler does not accept int arr[n] (it states that expression must have a constant value), since I have already defined it above, and what would be another way to write something like this?

1
2
3
4
5
6
7
8
9
10
11
12
  int main()
{
    int n;
    cin >> n;

    int arr[n];

    bubbleSort(arr, n);
    printf("Sorted array: \n");
    printArray(arr, n);
    return 0;
}


Thank you!
Last edited on
Hello geovoulg,

It really has nothing to do with the compiler, but more with C++ does not allow VLAs, (Variable Length Arrays). The compiler knows this and is telling you that the variable "n" needs to be a constant number.

You could do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
    constexpr int MAXSIZE{ 50 };

    int n;
    // <--- Needs a prompt.
    cin >> n;

    int arr[MAXSIZE];

    bubbleSort(arr, n);

    printf("Sorted array: \n");

    printArray(arr, n);

    return 0;
}

Then "n" could be the part of the array that is used so that you do not have to process the whole array.

If line 3 does not work for you change it to: const int MAXSIZE = 50;

Andy
Thanks Andy! I suppose I could use dynamic programming (dynamic array) as well, right?
Last edited on
Use a vector instead
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
    int n;
    cin >> n;

    vector<int> arr(n);

    bubbleSort(arr);
    printf("Sorted array: \n");
    printVector(arr);
    return 0;
}

Notice that I haven't passed n to bubbleSort or printVector(). The beauty of vectors is that they store their own size.
Hello geovoulg,

Yes. if you want to use "n" for the size of the array a dynamic array would be the better option.

Andy
@Andy

Sorry, dynamic array is not the better option in C++, I agree with dhayden std::vector is much better.

IMO we need to discourage the use of dynamic memory for beginners at least. Of course there are places where it is required, but not in place of existing STL containers.

However I do appreciate the effort you put in to helping others.

Regards :+)
Thank you for your replies all. No that's ok with the dynamic programming, I am in the process of starting to apply it in exercises anyway.
Topic archived. No new replies allowed.