使用的qsort在C字符数组 [英] Using qsort for character array in C
问题描述
我试图用的qsort
来排序字符数组。我不明白为什么这是行不通的。我有一个指向比较函数作为人
页面指定。有人可以告诉我有什么不对?谢谢。我的code:
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
pages specifies. Can someone please tell me what's wrong? Thanks. My code:
#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;
}
输出: dabce
当我想到 ABCDE
推荐答案
简单的错误。
使用的char *
而不是为int *
在 cmpfunc
。
int cmpfunc( const void *a, const void *b) {
return *(char*)a - *(char*)b;
}
当您使用为int *
,而不是的char *
,该地址被指向在
是PTED作为一个地址到 INT
间$ p $,而不是一个字符
。
When you use int*
, instead of char*
, the address pointed to by a
is interpreted as an address to an int
, not a char
.
您输入具有以下特点:
+---+---+---+---+---+
| b | c | e | a | d |
+---+---+---+---+---+
在十六进制,那些是:
+----+----+----+----+----+
| 62 | 63 | 65 | 61 | 64 |
+----+----+----+----+----+
^ ^
| |
a b
如果你把地址指向 A
和 B
为为int *
,假设一个 INT
需要4个字节的系统, *为(int *)A
可无论是
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
或
0X62 + 0X63*2^8 + 0X65*2^16 + 0X61*2^24
这取决于你是否有大端系统或小端系统。
depending on whether you have big endian system or a little endian system.
您同样可以计算什么 *为(int *)b
会。正如你所看到的,你已经遇到了意想不到的数量比较。由你开始比较这是在您输入的其他字节位置的数值的时候,你也在使用,你不应该使用的内存,而你达到未定义行为的领域。
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.
这篇关于使用的qsort在C字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!