#include <iomanip>
#include <iostream>
#include <Windows.h>
using namespace std;
template <class T>
void sort(int n, T a[]){
for(i=0;i<n-1;i++){
for(j=i;j<n;j++){
if(a[i] > a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
void main(){
int size;
cout<<" Please input the amount of numbers you would like to sort"<<endl;
cin>>size;
int Amta[size];
for(int i=0; i<size; i++){
cout<<"Please enter the "<<size+1<< "number";
cin>>Amta[i];
}
Sleep(100000);
}
I am trying to get the how many numbers the user would like to input from the user and store it in the variable size.
But when I initialize array Amta[size]
I get the following compile errors:
Expression must have constant value
and
C2057: expected constant expression" compile error.
You can't enter a non-constant value between the brackets when you declare your array:
int Amta[size];
Since you're getting size
from the user, the compiler can't tell ahead of time how much memory it needs for Amta
. The easiest thing to do here (especially for an exercise) is to just choose a relatively large value and make that the constant allocation, like:
int Amta[1024];
And then if you want to be careful (and you should) you can check if (size > 1024)
and print an error if the user wants a size that's beyond the pre-allocated bounds.
If you want to get fancy, you can define Amta
with no pre-set size, like int *Amta;
and then you allocate it later with malloc
:
Amta = (int *)malloc(sizeof(int) * size);
Then you must also free Amta
later, when you're done with it:
free(Amta);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments