I have been through this many times and I still can't get why the below code isn't working. It compiles without errors or warnings. I am using the MinGW64 compiler in Code::Blocks IDE 16.01. Basically, the exe file crashes after the input. In other words, after I enter the integers in the array, the program crashes. Sometimes, it gives random memory access errors / violations; other times, the program runs but the numbers are completely wrong; other times, it crashes without giving any reason or error.
/* includes and macros */
// required for input / output with minGW GCC
#include <stdio.h>
#define printf __mingw_printf
/* global declarations */
static short n, m;
/* function prototypes */
void selectionSortMax(int []);
int main()
{
/* declarations */
int arrayInput[n];
/* array input */
printf("How many integers do you want sorted by Selection Sort Max? ");
scanf("%hu", &n);
m = n;
printf("\nPlease enter the integers one by one, pressing the 'Enter' key after each input: ");
for(register short i = 0; i < n; i++)
{
scanf("%d", &arrayInput[i]);
}
/* selection and sort using the Selection Sort Max algorithm */
selectionSortMax(arrayInput);
/* print the sorted array */
for(register short i = 0; i < m; i++)
{
printf("[%d] ", arrayInput[i]);
}
return 0;
}
/* function definitions */
void selectionSortMax(int arrayInput[])
{
int max = 0, maxIndex, temp;
for(; n >= 1; n--)
{
// find max
for(register short i = 0; i <= n-1; i++)
{
if( (arrayInput[i] >= arrayInput[i+1]) && (max < arrayInput[i]) )
{
max = arrayInput[i];
maxIndex = i;
}
else if( (arrayInput[i+1] >= arrayInput[i]) && (max < arrayInput[i+1]) )
{
max = arrayInput[i+1];
maxIndex = i + 1;
}
}
// swap the largest integer with the last one in the array
temp = arrayInput[n-1];
arrayInput[n-1] = arrayInput[maxIndex];
arrayInput[maxIndex] = temp;
}
}
It looks like you're new here. If you want to get involved, click one of these buttons!
Comments
Correct answer is: fuck knows, because
n
at line 8 is assigned to garbage. At least put declaration after you get value ofn
.Okay. B00, the crashing problem was resolved as soon as I fixed the declaration of the variable length array but my algorithm is not working. Can anyone tell me why?