In the following code if I declare the variable-length array 'int array1[x]' before scanning the desired length of the array 'x', I receive ' segmentation fault (core dumped)' while execution. (compilation is error-free). I used strictly ANSI C99 standards by using option -std=c99 while compiling.
My question is Why can't I club all the declarations together?
// code to find a minimum value in a variable-length array
#include<stdio.h>
int minval(int [], int);
int main(void)
{
int x, i;
int minivalue;
printf("Enter the total number of array elements you wish to define?");
scanf("%i",&x);
int array1[x];
printf("Enter the elements now:");
for (i = 0; i < x; i++)
scanf("%i",&array1[i]);
minivalue = minval(array1, x);
printf("\nMinimum value in the array is = %i\n",minivalue);
return 0;
}
int minval(int array2[], int x)
{
int i;
int minivalue;
minivalue = array2[0];
for (i=0; i < x; i++){
if (minivalue > array2[i])
minivalue = array2[i];
}
return (minivalue);
}