I have written a simple program in C:
#include <stdio.h>
main(){
int a[20], b[20];
int n, i;
printf("Enter a number: ");
scanf("%d", &n);
for(int j=0; j<n; j++){
printf("Enter a number for a[%d]: ", j);
scanf("%d", a[j]);
printf("\n");
}
}
This code compiles but while running when n is greater than 2 and when input a second number in to the array an crash occurred.
I don’t underestant why it crashed, please explain it to me.
scanftakes a pointer to the place in which to store the value. I.e. the address ofa[j]. Soscanf("%d", &(a[j]) );, orscanf("%d", a+j);(Remember,a[j]is equivalent to*(a+j)).Also, there are various other issues with this. For starters, is it supposed to be
corc++? At the moment it isn’t really either (although it’s closer toc). And what happens if someone enters greater than20?If you’re wondering what was causing the crash, it was interpreting whatever value was in
a[j](which was just some uninitialised garbage) as an address, then trying to write to that (completely invalid) address. It doesn’t like this, and the operating system kills your program. This is called a segmentation fault.