字符缓冲区比较
我有两个字符缓冲区,我正在尝试比较它们的一部分。我有一个奇怪的问题。我有以下代码:
char buffer1[50], buffer2[60];
// Get buffer1 and buffer2 from the network by reading sockets
for(int i = 0; i < 20; i++)
{
if(buffer1[15+i] != buffer2[25+i])
{
printf("%c", buffer1[15+i]);
printf("%c", buffer2[25+i]);
printf("%02x", (unsigned char)buffer1[15+i]);
printf("%02x", (unsigned char)buffer2[25+i]);
break;
}
}
上面的代码是我的实际代码的简化版本,我没有复制粘贴到这里,因为它太长了。为了以防万一这可能有帮助,我通过读取套接字通过网络获取了这两个缓冲区。
问题是即使两个缓冲区相同,循环也会中断。为了检查缓冲区中的内容,我在 if 语句内添加了两个 print 语句。奇怪的是,printf 语句都为 %c 和 %02x 打印相同的值,但比较失败并且循环中断。
i have two char buffers which i am trying to compare parts of them. i am having a weird problem. i have the following code:
char buffer1[50], buffer2[60];
// Get buffer1 and buffer2 from the network by reading sockets
for(int i = 0; i < 20; i++)
{
if(buffer1[15+i] != buffer2[25+i])
{
printf("%c", buffer1[15+i]);
printf("%c", buffer2[25+i]);
printf("%02x", (unsigned char)buffer1[15+i]);
printf("%02x", (unsigned char)buffer2[25+i]);
break;
}
}
The above code is a simplified version of my actual code which I didnt copy-paste here because its too long. Just in case this might help, I got those two buffer over the network by reading sockets.
The problem is the loop breaks even when both the buffers are the same. To check what is in the buffers, I added the two print statements inside the if statement. And the weird thing is is, the printf statements both print the same value for %c and %02x, but the comparison fails and the loop breaks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(免责声明:我不是 C/++ 专家)
在我看来,当您查看数据时,数据正在发生变化。我想到了两个简单的问题:
(Disclaimer: I'm not a C/++ expert)
It seems to me like the data is changing while you're looking at it. Two quick questions come to mind:
我唯一看到的是时间问题。如果它们在 if 语句上不同,而在 print 语句上相同,则有人在中间更改了它们。
The only thing I see is a timing issue. If they are not the same on the if statement and they are the same on the print statement someone changed them in between.