[I checked "https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard". I know The latest version of the compiler can declare an array as a variable. But what I'm not sure about is ,in past versions of compilers, why new T[b];
works , but T Temp[b];
doesn't work.]
Are both 'Temp[b];' and 'T*temp = new T[b];' declared as variables? I don't know the difference between the two.
#include <iostream>
using namespace std;
template <class T>
void reverseArray(T a[], int b) {
T temp[b];
for (int j = 0; j < b; j++)
temp[b - 1 - j] = a[j];
for (int k = 0; k < b; k++)
a[k] = temp[k];
}
int main() {
int x[] = { 1, 2, 3, 4, 5 };
reverseArray(x, 5);
for (int i = 0; i < 5; i++)
cout << x[i] << " ";
}
To explain the codes
I have a problem in T temp[b];
Error Code
C2131 - expression did not evaluate to a constant //line6 , C3863 - array type 'type' is not assignable //line6
The above code builds well on online C++ compilers in 'https://www.onlinegdb.com/online_c++_compiler ' but it doesn't build in my computer's visual studio (V.S Community 2019 ver_16.8.2)
I searched for the reason. The reason is that ,in the previous version of C++11, it is impossible to declare the size of the array as a variable. The size of the array must be determined at the time of compile in the previous version of C++11
So, the error-correction method that I found was
1
. T temp[b]; --> T* temp = new T[b]; //line6
Use dynamic array
2
.
template <class T>
void reverseArray(T a[], int b) {
for (int i = 0; i < b / 2; i++) {
T temp = a[i];
a[i] = a[b - 1 - i];
a[b - 1 - i] = temp;
}
}
[Method2 Reference: "https://stackoverflow.com/questions/59330094/c-reverse-array-elements-using-dynamic-allocation-operators" used the algorithm in this address]
It works well by using above two methods in my V.S
But what i don't understand is that ,in method 1, is the size of the array(new T[b]) declared as variable? I don't know the difference from the code that I wrote first.
In array T Temp[b];
there is an error in my code because b is a variable. In new T[b];
, likewise, b is a variable too.
Please explain the difference between my first code and method 1. How the algorithm works