c++ - 数组+整数的指针 (C++)

标签 c++ c pointers buffer

我对C++不太熟悉,所以我想问一下,下面的代码会做什么(我在现有的C++项目中有它):

1: char* buf;
2: *buf = 0;
3: int readBytes = tcpSocket->read(buf, 10);
4: buf += readBytes;

解释很简单,从 TCP Socket 应该读取 10 个字节,并且读取的字节存储在 char* 缓冲区“buf”中。 返回值为读取的字节数。

但是为什么我需要第 4 行? 或者更好的是 4 号线在做什么? 根据我的理解,它正在破坏我的“buf”结果,不是吗?

我希望有人可以帮助我,也许可以解释一下,为什么我需要这行 4。

BR ThW

最佳答案

TCP 是一种协议(protocol),这意味着您接收的数据中没有消息边界。因此,人们可能无法在一次接收调用中获得所需的所有数据,而必须多次循环和读取。

通过做,例如buf += readBytes 将指针 buf 前进 readBytes 元素,因此下次接收数据时将写入上次接收调用留下的位置的。

除了使用和取消引用未初始化的指针之外,您还需要解决一些问题,即您无法在循环中的每次迭代中读取固定数量的字节,您需要减少也由 readBytes 接收数据。读取所有数据后,您还需要退出循环。

让我们将所有这些组合成一个很好的函数,该函数将始终读取请求的数据量,例如:

// tcpSocket is the socket to receive data from (I don't know the actual type)
// buffer is the destination buffer, where the received data should be written
// len is the number of bytes to receive
// Pre-condition: buffer must point to memory of at least len bytes
bool read_data(TCPSocketType* tcpSocket, char* buffer, size_t len)
{
    // Loop while there are still bytes to read
    while (len > 0)
    {
        ssize_t readBytes = tcpSocket->read(buffer, len);
        if (readBytes <= 0)
        {
            // There was an error (readBytes < 0)
            // Or the connection was closed (readBytes == 0)
            return false;
        }

        buffer += readBytes;  // Next position to write data into
        len -= readBytes;  // We don't need to read as much now
    }

    return true;  // Now we have read all of the data
}

关于c++ - 数组+整数的指针 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35891823/

相关文章:

c++ - 通过 IADS 删除 Active Directory 中的对象

c - getenv() 将环境返回为 null?

c - 尝试在 C 中释放字符数组的数组会导致双重释放或损坏

c++ - 用指针初始化 C++ 类是否安全?

c++ - 如何在给定 std::variant 的情况下检索模板参数包?

c++ - BST 递归查找高度

c - 内存分配

c++ - 我正在尝试从用户那里获取单个输入,但计算机以某种方式要求两个输入?

C - 单步执行结构指针的问题

c++ - 你如何制作一个带有纹理映射的立方体,在内部和外部显示不同的纹理