i'm having a little trouble using the qsort available in C to sort an array of strings i have in a struct of mine.
My code goes as follows:
typedef struct estrutura
{
int sp;
int numberOfEntries;
int entriesSize;
char* stack[26];
char** list;
}*estrutura;
void createStruct (estrutura l, int numberEntries, int sizeEntries)
{
l -> list = malloc (numberEntries * sizeof(char*));
l -> numberOfEntries = numberEntries;
l -> sp = 0;
l -> entriesSize = sizeEntries;
for (int i = 0; i < (l -> numberOfEntries); i++)
(l -> list)[i] = malloc ((sizeEntries + 1) * sizeof(char));
}
int cmpstr(void const *a, void const *b) {
char const *aa = (char const *)a;
char const *bb = (char const *)b;
return strcmp(aa, bb);
}
void addEntry (estrutura l, char* line)
{
strcpy((l -> list)[(l -> sp)],line);
(l -> sp)++;
}
void sortStruct (estrutura l)
{
qsort((l -> list)[0], l -> numberOfEntries, (l -> entriesSize) * sizeof(char), cmpstr);
}
void printStruct (estrutura l)
{
for (int i = 0; i < (l -> numberOfEntries); i++)
printf("%s\n",(l -> list)[i]);
}
void freeStruct (estrutura l)
{
for (int i = 0; i < (l -> numberOfEntries); i++)
free((l -> list)[i]);
free(l);
}
So my problem is: when i run a test in my main function:
int main ()
{
estrutura example = malloc (sizeof(struct estrutura));
createStruct(example,2,6);
char* name = malloc (6*sizeof(char));
strcpy(name,"A1234");
char* otherName = malloc(6*sizeof(char));
strcpy(otherName, "B1234");
addEntry(example,otherName);
addEntry(example,name);
printf("/////BEFORE SORTING//////\n");
printStruct(example);
sortStruct(example);
printf("/////AFTER SORTING//////\n");
printStruct(example);
freeStruct(example);
}
The output that i get before the sorting is as expected:
"A1234"
"B1234"
But after the sorting, the output i get is:
" " -> blank line
"B1234"
And this happens for every test i make. It just erases the first element and then doesn't sort at all. Any help would be appreaciated.