I am trying to implement a simple program, asking users to input the array length and numbers to fill up the array, then print out the array with printf.
If I use Method 1 and declare the array at the very beginning, the program will print out successfully but shows segmentation fault at the end.
If I use Method 2, declare the array after the user input numbersLength, there will be no segmentation fault.
What's the difference and why there is segmentation fault in method 1?
Any help would greatly be appreciated!
Method 1
#include<stdio.h>
int main()
{
int numbers[] = {};
int numbersLength;
printf("numbersLength: \n");
scanf("%d", &numbersLength);
for (int i=0 ; i < numbersLength; i++){
printf("number: \n");
scanf("%d", &numbers[i]);
}
for (int i=0 ; i < numbersLength; i++){
printf("%d \n", numbers[i]);
}
}
numbersLength:
5
number:
1
number:
2
number:
3
number:
4
number:
5
1
2
3
4
5
Segmentation fault
Method 2
#include<stdio.h>
int main()
{
int numbersLength;
printf("numbersLength: \n");
scanf("%d", &numbersLength);
int numbers[numbersLength];
for (int i=0 ; i < numbersLength; i++){
printf("number: \n");
scanf("%d", &numbers[i]);
}
for (int i=0 ; i < numbersLength; i++){
printf("%d \n", numbers[i]);
}
}
numbersis ? Any text book or online course will cover the basics. You can't learn C by trial and error.int numbers[] = {};That declares an array of 0 size. So accessing any elements in that array results in undefined behaviour. Arrays in C do not automatically grow in size.int numbers[] = {};is not valid C"error: zero or negative size array"