How to compare C++ string using qsort in c?

前端 未结 6 568
时光说笑
时光说笑 2020-12-21 08:49

I tried to learn the qsort function of the c-library stdlib. This is provided even in c++. But i dont understand how to use them for sorting

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-21 09:07

    The problem is that you give qsort an array of C++ strings. In your comparison function, you seem to except C strings, since you cast them to (const char*).

    Also, the third parameter of qsort, the size of data, you actually give wrong value. sizeof(obj[0].length()) will result in sizeof(size_t), which is obviously wrong. sizeof(obj[0]) would be more correct, but remember that qsort won't call copy constructor of string, which might lead to problems.

    I would suggest not to use qsort with C++ strings.

    See answer provided by PiotrNycz for correct solution.

提交回复
热议问题