I'm trying to sort an array of strings. I wrote my comparison function and tested it with single char* strings, but when I try and loop over an array of strings it fails, my code crashes internally in the qsort() function and I dont understand why.
Code:
/* sample.cpp */
#include <iostream>
using namespace std;
const int NUM_STRINGS = 10;
int compare(const void* p1, const void* p2); // for qsort()
int main()
{
char* arr_strs[] = { "test", "hi", "hello", "debug" };
char buf[80];
/* this part fails on the first iteration */
for(int i = 0; i < NUM_STRINGS; i++)
qsort(arr_strs[i], strlen(arr_strs[i]), sizeof(char), compare);
/* but this would work */
strcpy(buf, arr_strs[0]);
qsort(buf, strlen(buf), sizeof(char), compare);
/* I'm not sure if this would work, I havent tested it */
{
char* test = "helloworld";
qsort(test, strlen(test), sizeof(char), compare);
}
}
int compare(const void* p1, const void* p2)
{
return (*(char*)p1 - *(char*)p2);
}