If arrays in C are fixed in size, then how come this code is working properly? This code works but my teacher said I did it in a wrong way...
int main()
{
int n,element,i;
printf("Enter the size of Array : ");
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++){
printf("Enter %d no element : ",i+1);
scanf("%d",&a[i]);
}
printf("Enter the new element to be inserted at the End: ");
scanf("%d",&element);
n=n+1;
a[n-1]=element;
for(i=0;i<n;i++){
printf("%d\t",a[i]);
}
}
It does not work. At least not reliably. This is undefined behavior since you're accessing memory outside the array. If you don't go very far outside the array it often work, but it is very dangerous to do like that and the way you are handling it is not acceptable under any circumstances.
If you need to change the size, then use dynamic allocation like this:
int *a = malloc(n*sizeof(*a));
if (!a) { /* Handle error */ }
and then:
n=n+1;
// Using a void pointer, because this pointer should not be used for
// dereferencing
void *tmp = realloc(a, n*sizeof(*a));
if (!tmp) { /* Handle error */ }
a = tmp;
Actually, I would prefer dynamic allocation instead of using VLA:s any day. Just the fact that they removed the requirement for compilers to support them in moderrn C standards is a good indication that it is a bad idea to use them. And since the support for them is not mandatory anymore, using them MAY break your code in the future.