在C中使用qsort作为字符数组

use*_*227 9 c pointers function qsort

我正在尝试用来qsort对字符数组进行排序.我不明白为什么这不起作用.我有一个指向比较函数的指针,如man页面指​​定的那样.有人可以告诉我有什么问题吗?谢谢.我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

void AlphabetSoup( char str[] ) {
  qsort(str, (size_t) strlen(str), (size_t) sizeof(char), cmpfunc);
  printf("%s\n", str);
}


int main() {
  char str1[] = "bcead";

  AlphabetSoup(str1);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出: dabce我期待的时候abcde.

R S*_*ahu 8

简单的错误.

使用char*而不是int*in cmpfunc.

int cmpfunc( const void *a, const void *b) {
  return *(char*)a - *(char*)b;
}
Run Code Online (Sandbox Code Playgroud)

使用时int*,而不是char*指向的地址a被解释为a的地址int,而不是a char.

您的输入具有以下字符:

+---+---+---+---+---+
| b | c | e | a | d |
+---+---+---+---+---+
Run Code Online (Sandbox Code Playgroud)

在十六进制中,那些是:

+----+----+----+----+----+
| 62 | 63 | 65 | 61 | 64 |
+----+----+----+----+----+
^    ^
|    |
a    b
Run Code Online (Sandbox Code Playgroud)

如果您将指向的地址视为a和,假设系统中占用4个字节,则可以是bint*int*(int*)a

0X62*2^24 + 0X63*2^16 + 0X65*2^8 + 0X61
Run Code Online (Sandbox Code Playgroud)

要么

0X62 + 0X63*2^8 + 0X65*2^16 + 0X61*2^24
Run Code Online (Sandbox Code Playgroud)

取决于您是否具有大端系统或小端系统.

您可以类似地计算*(int*)b将会是什么.如您所见,您已经遇到意外的数字比较.当您开始比较输入的其他字节位置的值时,您还使用了不应该使用的内存,并且您正在达到未定义行为的领域.