-1

I typed the following code to sort the components of an int array. It does not show any error but does stops working abruptly. The error is generally after entering 7-8 inputs which shows that program.exe has stopped working. Does it has anything related to the code ?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n,a[n],i,j,temp;
    printf("Enter number of inputs.\n");
    scanf("%d",&n);
    printf("Enter inputs\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(a[i]<a[j])
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
    printf("Numbers in descending order are:\n");
    for(i=0;i<n;i++)
    {
        printf("%d\n",a[i]);
    }
    return 0;
}
edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47
  • 6
    `prog.cc:6:12: warning: variable length arrays are a C99 feature [-Wvla-extension] prog.cc:6:13: warning: variable 'n' is uninitialized when used here [-Wuninitialized]` – hellow Sep 04 '18 at 14:49
  • https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Jabberwocky Sep 04 '18 at 14:51
  • 3
    Welcome to Stackoverflow. The first thing you should do is, fix your program and always listen to your compiler warnings (and notes)! [Just enable them](https://stackoverflow.com/questions/2574200/gcc-is-using-werror-and-pedantic-considered-good-practice). Next thing, [try to debug simple programs yourself](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems), it is not that hard and will save you hours of asking ;) – hellow Sep 04 '18 at 14:52

1 Answers1

0

The problem is here:

int n, a[n], i, j, temp;

Declarations are done sequentially. If you write this in a slighly more readably (but equivalent form) you'd have this:

int n;
int a[n];    // here the variable n has not yet been initialized
             // it contains an indeterminate value, and therefore the a array
             // will have an indeterminate size and the program will have
             // so called "undefined behaviour " (google that)
int i;
...

You should write the beginning of your program like this:

int main()
{
    int n,i,j,temp;
    printf("Enter number of inputs.\n");
    scanf("%d",&n);
    int a[n];                  // now n has a determinate value
    printf("Enter inputs\n");

Disclaimer: no error checking is done for brevity.

Always compile with warnings enabled and listen to them. Many of them are actually errors. Especially the warning variable 'somevar' is uninitialized when used here is always an error.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115