Insertion Sort Error in C++

TD P { margin-bottom: 0in; }P { margin-bottom: 0.08in; }TT.cjk { font-family: "WenQuanYi Zen Hei Sharp",monospace; }A:link { } I am trying to run this program for Insertion Sort, But don't know that why I am getting following Error

#include<iostream>
int main(){
int i,j,key,n;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++) scanf("%d",&a);
for(j=1;j<n;j++){
key=a[j];
i=j-1;
while(i>=0&&a>key){
a[i+1]=a;
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.

It's telling you the problem: You're not allowed to make a variable size array like that. 'int a[5]' type arrays have to be fixed in size at compile time, you can't pick the size later.

Do this instead:

int *a=new int[n];

Which you can use just like an array afterwards.

in fact, if you have the oppertunity to use C++11, it is a solution to this old problem. The new standard of C++ says variable size arrays are aloud, if you supply a certain keyword(i forgot), which indicates to the compiler that the programmer knows for sure the variable is not going to be 0 or negative value.

...which will cause it to blow up or go bananas whenever you use a compiler that doesn't. I've had to "fix" several pieces of code like that.

It is true that many compiler (or maybe safe to say none) do support the full standard of C++11. And many do not even have decent support for basic C++11 standard, so I guess we have to stick to the C++98 solution with new.