I’ve got an array of structs, and I’m trying to sort it by price using selection sort. I’m consistently getting a ECX_BAD_ACCESS signal.
This is what I’ve got:
#include <iostream>
#include <string>
using namespace std;
So thing is just a struct with a name and a price. The price is what I want to sort the structs by
struct Thing
{
std::string name;
double price;
};
Right now, the main method just checks to make sure that the sortThing function is working.
Thing *sortThing(Thing input[], int size);
int main ()
{
Thing *stuff = new Thing[3];
stuff[0].name = "middle";
stuff[0].price = 2.00;
stuff[1].name = "last";
stuff[1].price = 3.00;
stuff[2].name = "first";
stuff[2].price = 1.00;
stuff = sortThing(stuff, 3);
cout << stuff[0].name + " " + stuff[1].name + " " + stuff[2].name;
return 0;
}
This is where the problem is. It complains about the line where I assign input[maxIndex].name to output[i].name, saying: “Program Received ‘EXC_BAD_ACCESS'”
Thing *sortThing(Thing input[], int size)
{
Thing *output = new Thing[size];
Thing nullThing;
nullThing.name = "&nullThing";
int min = 0;
int minIndex;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (input[j].name.compare("&nullThing") != 0 && input[j].price <= min) minIndex = j;
}
output[i].name = input[minIndex].name;
output[i].price = input[minIndex].price;
input[minIndex] = nullThing;
minIndex = 0;
min = 0;
}
return output;
}
Any help is appreciated
I think your loop for determining
minIndexis incorrect… Since all prices are >= 0, you will never setminIndex, and since you never initialized it, it’s value can be anything. Most likely in your case the value is outside the range of the array and effectively having an array out of bounds error.Might want to look into some sorting algorithms.