-1

I am trying to sort a pointer array of characters using qsort and keep getting a segmentation fault when I compile. I will post the code for my qsort call and the compare function and any help would be greatly appreciated.

//count declaration
size_t count = (sizeof (strPtrsQsort)/sizeof (*strPtrsQsort));
//function call
qsort ((char *)ptr, size, sizeof(char), compare);

//compare function
int compare (const void *a, const void *b)
{
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp (*ia, *ib);
}
djv
  • 15,168
  • 7
  • 48
  • 72
Asron
  • 7
  • 2
  • What is `count`, what is `strPtrsQsort` and are they present in the code snippet you posted? They are not used anywhere in `qsort`. – AnT stands with Russia Oct 09 '14 at 18:19
  • 2
    Why are you using C strings, raw arrays, and C's `qsort` in C++? Use `std::vector` and `std::sort`. – crashmstr Oct 09 '14 at 18:21
  • 1
    If you are trying to sort an array of pointers, why the array element size is passed to `qsort` as `sizeof(char)`??? How is `ptr` declared? Why are you converting it to `char *` before passing to `qsort`? – AnT stands with Russia Oct 09 '14 at 18:24

2 Answers2

0

Judging by your qsort call, you are sorting an array of char elements: the base pointer type is passed to qsort as char * value and the element size is sizeof(char). However, your comparison function is written for an array of pointers to char. That's completely incorrect and inconsistent. That is what is causing the crash.

In the accompanying text you state that you are "trying to sort a pointer array of characters". Why in that case are you specifying the element size as sizeof(char) and not as, say, sizeof (char *)?

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • Thanks for your help. I'm pretty new to pointers am just getting ahold of dereferencing. That helped a lot. – Asron Oct 09 '14 at 18:46
0

Note that even when you're required to work with C-style raw arrays you can still use C++ STL algorithms, since pointers are in fact RandomAccessIterators. For example, this works:

#include <algorithm>
#include <iostream>
#include <cstring>

static
bool compare(const char *a, const char *b)
{
    return std::strcmp(a, b) < 0;
}

int main()
{
    const char *stringarray[] = {
        "zyxulsusd",
        "abcdef",
        "asdf"
    };

    std::sort(stringarray, stringarray + 3, compare);
    //                      -----------^
    // Just like a normal iterator the end iterator points
    // to an imaginary element behind the data.

    for(int i = 0; i < 3; i++) {
        std::cout << stringarray[i] << std::endl;
    }

    return 0;
}

The primary advantage of this approach is type safety and it avoids thus most pitfalls common with C-style functions like qsort.

dom0
  • 7,356
  • 3
  • 28
  • 50