Reputation: 119
I have written a simple C program in Eclipse that, when run, only executes correctly about 1 out of 10 times. The rest of the time, the program is terminated with the error value "-1.073.741.819". It does not respond to any printf()
that precedes the location in question. If I execute my program now, commenting out the for loop and the function call with pointer, it always works.
The source code is the following:
#include <stdio.h>
int getMinPos(int *argv, int argc, int startPos);
int* swap(int *argv, int firstIndex, int secondIndex);
int* selectionSort(int *argv, int argc);
int getMinPos(int *argv, int argc, int startPos)
{
int max = argv[startPos];
for (int i = startPos; i < argc; i++)
{
if (argv[i] < argv[max])
{
max = i;
}
}
return max;
}
int* swap(int *argv, int firstIndex, int secondIndex)
{
int temp = argv[firstIndex];
argv[firstIndex] = argv[secondIndex];
argv[secondIndex] = temp;
return argv;
}
int* selectionSort(int *argv, int argc)
{
for (int i = 0; i < argc; i++)
{
swap(argv, i, getMinPos(argv, argc, i));
}
return argv;
}
int main(int argc, char **argv)
{
printf("Test\n"); // no printing even before function call
int x[] = {3,1,2,5,2,78,3421,34};
int *p = selectionSort(x, sizeof(x) / sizeof(x[0]));
for (int i = 0; i < sizeof(x) / sizeof(x[0]); i++)
{
printf("Outcome: %d\n", p[i]);
}
return 0;
}
Thanks in advance!
Upvotes: 1
Views: 52
Reputation: 119
Fixed version:
#include <stdio.h>
int getMinPos(int *arrv, int arrc, int startPos);
void swap(int *arrv, int firstIndex, int secondIndex);
void selectionSort(int *arrv, int arrc);
int getMinPos(int *arrv, int arrc, int startPos)
{
int max = startPos;
for (int i = startPos; i < arrc; i++)
{
if (arrv[i] < arrv[max])
{
max = i;
}
}
return max;
}
void swap(int *arrv, int firstIndex, int secondIndex)
{
int temp = arrv[firstIndex];
arrv[firstIndex] = arrv[secondIndex];
arrv[secondIndex] = temp;
}
void selectionSort(int *arrv, int arrc)
{
for (int i = 0; i < arrc-1; i++)
{
swap(arrv, i, getMinPos(arrv, arrc, i));
}
}
int main(int argc, char **argv)
{
int x[] = {3,1,2,5,2,78,3421,34};
int size = sizeof(x) / sizeof(x[0]);
selectionSort(x, size);
for (int i = 0; i < size; i++)
{
printf("Outcome: %d\n", x[i]);
}
return 0;
}
I have made some other improvements to the source code as well.
Upvotes: 1