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
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.