1

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);
}
8
  • 4
    There are 2 elements in the array, but you are sorting only 1, it should be something like qsort(nova_str, 2, sizeof *nova_str, string_cmp); . Commented May 14, 2020 at 19:12
  • 1
    You sort 1 element only, and you pass the wrong element size as sizeof(char *)*1024. That is 1024 time the size of a pointer. qsort(nova_str, 2, sizeof nova_str[0], string_cmp) would work. Commented May 14, 2020 at 19:14
  • 2
    Also qsort(nova_str, 2, 1024, strcmp); will work without making your own comparator function. Commented May 14, 2020 at 19:19
  • 1
    your compare function is wrong, qsort (if called correctly as suggested) will pass just the pointer your strings, not a pointer to pointer. Commented May 14, 2020 at 19:23
  • 1
    @WeatherVane using strcmp directly will emit a warning of "incompatible pointer type" (at least on gcc) Commented May 14, 2020 at 19:41

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.