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);
}
qsort(nova_str, 2, sizeof *nova_str, string_cmp);.1element only, and you pass the wrong element size assizeof(char *)*1024. That is1024time the size of a pointer.qsort(nova_str, 2, sizeof nova_str[0], string_cmp)would work.qsort(nova_str, 2, 1024, strcmp);will work without making your own comparator function.qsort(if called correctly as suggested) will pass just the pointer your strings, not a pointer to pointer.strcmpdirectly will emit a warning of "incompatible pointer type" (at least ongcc)