Reputation: 505
So i have an array of strings called nova_str[50][1024]
and what i want is to sort it using qsort the problem is that its not sorting anything.
My output:
* fcb
* bvb
Correct output:
* bvb
* fcb
as you can see the array isnt being sorted and i cant dont know why, so any help would be appreciated.
Program:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int string_cmp (const void * a, const void * b ) {
const char * pa = *(const char * const * ) a;
const char * pb = *(const char * const * ) b;
return strcmp(pa,pb);
}
void print_array(char array[][1024], int len)
{
int i;
for(i=0; i<len; i++)
{
printf("* %s\n",array[i]);
}
}
int main(void)
{
char nova_str[50][1024];
strcpy(nova_str[0],"fcb");
strcpy(nova_str[1],"bvb");
qsort(nova_str,1, sizeof(char *)*1024, string_cmp);
print_array(nova_str,2);
}
Upvotes: 1
Views: 1123
Reputation: 3197
This will work.
// You are getting a pointer from qsort, not a pointer to a pointer.
int string_cmp (const void * a, const void * b ) {
const char * pa = (const char *) a;
const char * pb = (const char *) b;
return strcmp(pa,pb);
}
void print_array(char array[][1024], int len)
{
int i;
for(i=0; i<len; i++)
{
printf("* %s\n",array[i]);
}
}
int main(void)
{
char nova_str[50][1024];
strcpy(nova_str[0],"fcb");
strcpy(nova_str[1],"bvb");
// the size is 2, not 1
// you also want the correct size of the elements
// getting the size of the first element will ensure this
qsort(nova_str,2, sizeof(nova_str[0]), string_cmp);
print_array(nova_str,2);
}
I hope that this helps.
Upvotes: 4