Insertion Sort Runtime Error

I am trying to run this program for Insertion Sort, But some how I am getting some problem:


#include<iostream>
int main(){
int i,j,key,n;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++) scanf("%d",&a[i]);
for(j=1;j<n;j++){
key=a[j];
i=j-1;
while(i>=0&&a[i]>key){
a[i+1]=a[i];
i=i-1;
}
a[i+1]=key;
}
for(j=0;j<n;j++) printf("%d ",a[j]);
return 0;
}

Error
In function 'int main()':
Line 10: error: ISO C++ forbids variable-size array 'a'
compilation terminated due to -Wfatal-errors.

http://live-project-training.in/
Last edited on
yes, it is like the error says.

So either you declare the array with a constant dimension (and check if n is within)
or you use a dynamic array like so:
1
2
3
4
5
int *a;
scanf("%d",&n);
a = new int[n];
...
delete[] a;
Standard C++ allow only arrays which size is known at the compile time: you can do something like int a[10]; or const int n = 10; int a[n]; but not int n; cin >> n; int a[n];

You should use either standard automatic containers or allocate memory yourself: int* a = new int[n];
Do not forget to deallocate array when you done with it: delete[] a;
Topic archived. No new replies allowed.