是的,我想将 qsort() 函数与两个字符串一起使用,这些字符串很可能会作为字符数组进行测试。当我运行它时,我在第 151 行的 qsort.c 中得到一个未处理的异常:
if (__COMPARE(context, lo, mid) > 0) {
swap(lo, mid, width);
}
这是我的代码:
#include <iostream>
#include <iomanip>
using namespace std;
struct SaleSlip{
char name[20];
int ProdID;
double value;
};
int compare(void const *a, void const *b);
ostream& operator<<(ostream& out, SaleSlip& sales);
int main(){
SaleSlip sales[17] = {
{"Eric", 1, 200000.00},
{"Sookie", 2, 200.00},
{"Sookie", 4, 200.50},
{"Bill", 3, 5000.00},
{"Bill", 5, 7500.00},
{"Tara", 4, 350.50},
{"Eric", 2, 200.00},
{"Tara", 2, 200.00},
{"Tara", 4, 350.50},
{"Bill", 5, 2500.00},
{"Sookie", 1, 50000.00},
{"Sookie", 2, 200.00},
{"Eric", 5, 10000.00},
{"Tara", 2, 200.00},
{"Tara", 4, 150.50},
{"Bill", 5, 1000.00},
{"Sookie", 4, 400.50}
};
cout << "The array before sorting is: " << endl;
for(int i = 0; i < 17; i++)
cout << sales[i];
qsort(sales[0].name, 17, (sizeof(sales)/sizeof(char*)), compare);
cout << "The array after sorting is: ";
system("pause");
return 0;
}
ostream& operator<<(ostream& out, SaleSlip& sales){
out << setiosflags(ios::left | ios::fixed) << setw(7) << sales.name << setw(3) << sales.ProdID
<< setprecision(2) << sales.value << endl;
return out;
}
int compare(void const *a, void const *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
我正在测试比较正确吗?我正确调用 qsort 吗?