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);
}
malloc).int a[x]is not considered valid. That's because it depends on a dynamic allocation. That's because x's value is not known at compile time. If the value of x is known at compile time, it is valid. I suspect that what is happening when you place it after is that a GCC extension is automatically converting it to Emanuele Bezzi's answer. When it's placed before, GCC is doing the same, exceptx1is not initialized and therefore the malloc has the potential to go horribly wrong.