字符缓冲区比较

发布于 2024-10-23 20:15:11 字数 643 浏览 2 评论 0原文

我有两个字符缓冲区,我正在尝试比较它们的一部分。我有一个奇怪的问题。我有以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

友欢 2024-10-30 20:15:11

(免责声明:我不是 C/++ 专家)

在我看来,当您查看数据时,数据正在发生变化。我想到了两个简单的问题:

  1. 如果您在调试器中运行它,并逐步执行循环,它还会发生吗?如果没有,那么我强烈怀疑我的第二个问题会引导您找到答案。
  2. 读操作是异步的吗?当您在 for 循环内时,似乎仍在读取数据,这意味着您没有等待读取完成。

(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:

  1. If you run this in the debugger, and go over the loop step-by-step, does it still happen? If it doesn't, then I strongly suspect my second question will lead you to the answer.
  2. Is the read operation asynchronous? It seems like data is still being read while you're inside the for loop, meaning you didn't wait for the read to finish.
待"谢繁草 2024-10-30 20:15:11

我唯一看到的是时间问题。如果它们在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文