本文介绍了memcmp返回值的大小是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚好调试了一个令人讨厌的错误:在我自己的PC(Windows 7 x64,MinGw)上,当比较数组成员时,我的C程序将使用memcmp成功地对数组进行排序.

I just happened to debug an incredibly nasty error: On my own PC (Windows 7 x64, MinGw) my C program would successfully sort an array using the memcmp when comparing array members.

我的函数使用了冒泡排序算法,其骨架看起来像这样:

My function used bubble sort algorithm and it's skeleton would look like this:

void array_sort(ArrayMap *array, char direction) {
    make sure direction is +1 or -1 only
    define some variables
    for(...) {
         for(...) {
             cmpres = memcmp(elm1, elm2, sizeOfElement);
             if (cmpres!=0&&cmpres!=direction)
             {
                 SWAP here
             }
         }
}

现在,在我的PC上,memcmp已返回-101,在另一台计算机上它已返回-505.通过与direction进行比较,我导致排序完全错误.

Now while on my PC, the memcmp has returned -1, 0 and 1 on another it returned -5, 0 and 5. By comparing this with direction I caused the sorting to go totally wrong.

但是我想知道,memcmp的返回值的绝对值(即大小)到底是什么意思?

But I wonder, what does the absolute value (that is, the size) of the return value of memcmp actually mean?

www.cplusplus.com :

没有提及大小,他们只是通过说大于零来确保不要对+ -1出错.

No mention of the size, they just make sure not to be wrong about +-1 by saying greater than zero.

推荐答案

结果幅度特定于实现,因此它没有可移植的含义,您不应依赖它. memcmp()函数只能保证返回正,负或零值.

The result magnitude implementation-specific, so it has no portable meaning and you should not rely on it. The memcmp() function is only guaranteed to return a positive, negative, or zero value.

之所以允许它具有任何值,是因为可以这样定义memcmp():

The reason why it is allowed to have any value is so memcmp() can be defined like this:

// Types changed to "char" to simplify code.
int memcmp(const unsigned char *x, const unsigned char *y, size_t n)
{
    for (size_t i = 0; i < n; i++) {
        int diff = x[i] - y[i];
        if (diff)
            return diff;
}

但是它也可以通过使用例如SSE来实现,并且返回值将有所不同.

But it can also be implemented by using, e.g., SSE, and the return value will be different.

这篇关于memcmp返回值的大小是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-13 10:31