0
Qt 6.2.1 MinGW

I have 2 arrays, header FirstArray and body SecondArray. I know that copy-paste, isn't good in programming, so at first, did so :

int main(int argc, char *argv[]) 
{
    QCoreApplication a(argc, argv);
    const QByteArray FirstArray=QByteArray(std::begin<char>({static_cast<char>(0xA5), 0x5A, static_cast<char>(0xB5), 0x5B}), 4);
    const QByteArray SecondArray=QByteArray(FirstArray+std::begin<char>({0x18, 0x00, 0x01, static_cast<char>(0x9B), 0x03, 0x09, 0x00, 0x19, static_cast<char>(0x91)}), 13);
    qDebug()<< SecondArray.toHex();

    return a.exec(); 
}

I expected the result:

"a55ab55b1800019b0309001991"

But in output I see:

"a55ab55b1800adbaababababab"

Then I rewrite the second QByteArray initialization, and remove plus operation in constructor:

const QByteArray SecondArray=QByteArray(std::begin<char>({static_cast<char>(0xA5), 0x5A, static_cast<char>(0xB5), 0x5B, 0x18, 0x00, 0x01, static_cast<char>(0x9B), 0x03, 0x09, 0x00, 0x19, static_cast<char>(0x91)}), 13);

I get:

"a55ab55b1800019b0309001991"

Why does it's happed in the first case? How to write correctly?

  • you already know how to get correct output, no? – 463035818_is_not_an_ai Dec 22 '21 at 08:52
  • 2
    The addition operator expects the right-hand operand to be a null-terminated string. (How did you expect it to determine how many elements there are?) You are probably suffering from undefined behaviour. – molbdnilo Dec 22 '21 at 08:52
  • @463035818_is_not_a_number yes I can copy the header to all my arrays, but I want to understand why the first variant works not correctly. It will help me to edit the header in future –  Dec 22 '21 at 08:55
  • @molbdnilo okay, and how I can write a correct initialization in the constructor –  Dec 22 '21 at 08:57

1 Answers1

2

As mentioned in a comment, you are calling

const QByteArray operator+(const QByteArray &a1, const char *a2)

Which, per its documentation:

Returns a byte array that is the result of concatenating byte array a1 and string a2.

It excepts a2 to point to a null-terminated string.

You can rearrange the concatenation to

FirstArray + QByteArray(std::begin<char>({0x18, ......

To call the other overload which does not rely on null-termination of a c-string.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185