0

If I want to give 10 elements, I scan how_many as 10.

But as soon as I enter the third value, the program crashes and returns some long negative value. I don't know where is the problem.

int main()
{
    int how_many,k;
    int data[how_many];

    printf("Enter the number of values to be sorted..: ");
    scanf("%d",&how_many);
    printf("Enter the values one by one..:\n");

    for (k=0;k<how_many;k++)
    {
        scanf("%d",&data[k]);
        printf("data[%d]=%d\n",k,data[k]);
    }

    return 0;
}
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39

1 Answers1

0

When you define int data[how_many] the variable how_many is still uninitialized.

Just define the array after you obtain the value from the user, but only if the scanf succeeded and the value is positive.

int how_many,k;

printf("Enter the number of values to be sorted..: ");
if ( scanf("%d",&how_many) && how_many > 0 )
{
    int data[how_many];
    /* ... */
}

But VLAs (variable length arrays) are a little dangerous: what if the user inserts 2000000000? You will have to check for a reasonable maximum value, too:

#define MAX 1000

/* ... */

if ( scanf("%d",&how_many) && how_many > 0 && how_many <= MAX )
{
    int data[how_many];
    /* ... */
}

That's why VLAs, that have been removed from the standard since C11, are not the best choice in this scenario. I suggest just defining the array statically

 int data [MAX];

Or dynamically:

int *data = malloc ( MAX * sizeof( int ) );
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39