gpt4 book ai didi

c - memcmp 返回值的大小是什么意思?

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:09 27 4
gpt4 key购买 nike

我刚好调试了一个令人难以置信的严重错误:在我自己的 PC(Windows 7 x64,MinGw)上,我的 C 程序在比较数组成员时使用 memcmp 成功地对数组进行了排序。

我的函数使用了冒泡排序算法,它的框架如下所示:

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 进行比较,我导致排序完全错误。

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

来自www.cplusplus.com :

Returns an integral value indicating the relationship between the content of the memory blocks: A zero value indicates that the contents of both memory blocks are equal. A value greater than zero indicates that the first byte that does not match in both memory blocks has a greater value in ptr1 than in ptr2 as if evaluated as unsigned char values; And a value less than zero indicates the opposite.

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

最佳答案

documentation说:

The memcmp() function shall return an integer greater than, equal to, or less than 0, if the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2, respectively.

它并没有说它会返回 -1 或 1。它究竟返回什么取决于实现。

更新:

在实现比较函数时,你经常会这样写:

return a[i] - b[i];

代替:

if (a[i] > b[i])
return 1;
else
return -1;

这是解释返回数字的一种可能的实现方式。

关于c - memcmp 返回值的大小是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23618328/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com