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;
}
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()
{
constexprint 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: constint MAXSIZE = 50;
Sorry, dynamic array is not the better option in C++, I agree with dhaydenstd::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.