C++ 对象指针改变位置

标签 c++ c pointers

我有一个函数需要两个指针,一个指向字符串对象,一个指向自定义 KCData 对象:

void KCConverter::dataToHexStringBuf(std::string *hexStringBuf, KCData *data) {
    char hexBuf[2];
    size_t position = data->getPosition();
    size_t length = data->getLength();
    uint8_t *copy = new uint8_t[data->getLength()];
    memcpy(copy, data->bytes, data->getLength());

    uint8_t current;
    for (size_t i = position; i < length; i++) {
        std::cout << "Reading char " << i << std::endl;
        current = copy[i];
        sprintf(hexBuf, "%02X", current);
        hexStringBuf->push_back(hexBuf[0]);
        hexStringBuf->push_back(hexBuf[1]);
    }
    data->setPosition(data->getLength());
}

但是 KCData 指针的值在 for 循环中发生变化:

第一次迭代: First iteration

第二次迭代: enter image description here

第三次迭代: enter image description here

但是,如果我取消注释 sprintf(hexBuf, "%02X", current); 行,指针不再改变。但为什么是sprintf更改 data 的指针地址????

P.S.:如果您否决了我的问题,最好了解原因,以便我可以改进我的问题:)

最佳答案

您溢出了hexBuf[]:

char hexBuf[2]; // 2 bytes long
...
    sprintf(hexBuf, "%02X", current); // Writing 3 bytes

您必须在输出字符串的长度中包含空字符 \0。解决方案是使 hexBuf[] 长度至少为 3 个字节。

关于C++ 对象指针改变位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30426410/

相关文章:

c++ - BSP 树是否适用于单个透明对象?

c - HexRays - "__OFSUB__()"的用途是什么?

我可以在 C 结构中声明结构引用的动态数组吗?

将 int 转换为字符串指针 C

c++ - 为什么我们不能在 C 或 C++ 代码中使用直接寻址?

c++ - 为什么1个元素的数组允许2k个元素?

c++ - 使用外部条件修改序列操作

c++ - 在将其大小作为参数传递的类中初始化 vector

c++ - glm::ivec2 作为无序映射中的键

c - 输入不匹配的字符串时,Scanf 在 while 循环中不起作用