Search code examples
c++qtqbytearray

Replace method changes size of QByteArray


I want to manipulate a 32 bit write command which I have stored in a QByteArray. But the thing that confuses me is that my QByteArray changes size and I cannot figure out why that happens.

My code:

const char CMREFCTL[] = {0x85,0x00,0x00,0x0B};
QByteArray test = QByteArray::fromRawData(CMREFCTL, sizeof(CMREFCTL));

qDebug()<<test.toHex();

const char last1 = 0x0B;
const char last2 = 0x0A;

test.replace(3,1,&last2);
qDebug()<<test.toHex();
test.replace(3,1,&last1);
qDebug()<<test.toHex();

Generates:

"0x8500000b"
"0x8500000a0ba86789"
"0x8500000ba867890ba86789"

I expected the following output:

"0x8500000b"
"0x8500000a"
"0x8500000b"

Using test.replace(3,1,&last2,1) works but I dont see why my code above dont give the same result.

Best regards!


Solution

  • Here is the documentation for the relevant method:

    QByteArray & QByteArray::replace ( int pos, int len, const char * after )

    This is an overloaded function.

    Replaces len bytes from index position pos with the zero terminated string after.

    Notice: this can change the length of the byte array.

    You are not giving the byte array a zero-terminated string, but a pointer to a single char. So it will scan forward in memory from that pointer until it hits a 0, and treat all that memory as the string to replace with.

    If you just want to change a single character test[3] = last2; should do what you want.