This program prints "Scanf Test #0 and 1" over and over
This is a consequence of not checking the result of scanf
. If scanf
cannot read an integer, then it leaves the stream untouched and reports failure. You don't check for this, so it worked once and failed 9 times.
If you enter 10 integers it will work fine; however clearly you're entering some other stuff such as letters which is causing the extraction of an integer to fail.
When there's a single conversion specification ("%d"
) in the format string, scanf
can return:
1
- success0
- junk characters entered- EOF - stream error
You should check this value and take appropriate action. You could just abort the program if it is not 1
, although it would be pro to clear the junk and ask again in case 0
.
Moving onto the actual sort. Your interface is weird as you pass N-1
to the function, and then have the function access 1 item beyond the end of the array. It would be clearer to do selection_sort(N, a)
, and then inside the function, high = n-1
and for (i = 0; i < n-1; i++)
etc.
Now, there is a subtle issue with the line:
void selection_sort(int n, int a[n])
This line does not match the prototype; you can fix your problem by replacing the line with:
void selection_sort(int n, int a[])
The original version caused the program to behave unexpectedly for me, but only if I invoke gcc in default mode (i.e. not C-standard compliant). There must be some sort of GNU extension in play that is causing trouble with int a[n]
.
In Standard C, the original code should work (and does, if gcc is invoked in standard mode via -std=c99
, which is something I'd strongly recommend doing anyway).