C qsort not working correctly

后端 未结 4 2162
北荒
北荒 2020-12-16 16:42

I don\'t know what I\'m doing wrong but the following code does not sort the array properly.

#include 
#include 

int compare(         


        
4条回答
  •  臣服心动
    2020-12-16 17:13

    Yeah, your "comparison" overflows. :(

    Reason:

    When you subtract a negative number from a positive number, your result is not necessarily positive; if it can't be represented in the data type, it'll "wrap around" the other side.

    Example:

    If your integer can only hold from -8 to 7 (4 bits), then what happens when you compare 4 to -4?
    Well, you get 8, which is 1000 in binary, which is -8. So 4 is less than -4.

    Moral:

    Don't do subtraction instead of comparison, even if they tell you "look how cool this is" at school!

提交回复
热议问题