Using qsort for character array in C

后端 未结 3 867
我在风中等你
我在风中等你 2021-01-05 01:28

I\'m trying to use qsort to sort a character array. I can\'t see why this is not working. I have a pointer to the compare function as the man pag

3条回答
  •  执笔经年
    2021-01-05 02:12

    Simple error.

    Use char* instead of int* in cmpfunc.

    int cmpfunc( const void *a, const void *b) {
      return *(char*)a - *(char*)b;
    }
    

    When you use int*, instead of char*, the address pointed to by a is interpreted as an address to an int, not a char.

    Your input has the following characters:

    +---+---+---+---+---+
    | b | c | e | a | d |
    +---+---+---+---+---+
    

    In hex, those are:

    +----+----+----+----+----+
    | 62 | 63 | 65 | 61 | 64 |
    +----+----+----+----+----+
    ^    ^
    |    |
    a    b
    

    If you treat the addresses pointed to a and b as int*, assuming an int takes 4 bytes in your system, *(int*)a can be either

    0X62*2^24 + 0X63*2^16 + 0X65*2^8 + 0X61
    

    or

    0X62 + 0X63*2^8 + 0X65*2^16 + 0X61*2^24
    

    depending on whether you have big endian system or a little endian system.

    You can similarly compute what *(int*)b would be. As you can see, you are already running into unexpected number comparisons. By the time you start comparing the values that are at other byte locations of your input, you are also using memory that you are not supposed to use, and you are reaching the realms of undefined behavior.

提交回复
热议问题