#include<stdio.h>
int main(){
int n;
printf("Enter the number:");
scanf("%d",&n);
int array[n];
for (int i=0;i<=n;i++){
printf("%dEnter the number:",i);
scanf("%d",&array[i]);
}
for (int i=n;i>=0;i--){
printf("%d\n",array[i]);
}
}
Where the size is defined to given number, but then the size is getting increased in while putting values inside the loop. Expecting the array to be accepting only 5 values but it is accepting more than 5.
The first loop writes to array
array[n]out of bounds (loop executes n+1 times). This is undefined behavior. It will likely overwrite unrelated memory and often that cause a segfault.Arrays in C are 0 indexed so the first element is
array[0]and the last isarray[n-1].The revised loop below is the standard idiom in C; if it's anything else a seasoned C developer will review it with extra care.
The 2nd loop read out of bound
array[n](n+1). This is undefined behavior.Check that n>=1 and reasonable size otherwise you program may crash running out of stack space.
Check the return value of
scanf()otherwise you may be operating on uninitialized variables which is undefined behavior.Formatted your code for readability (it matters).
example session: