Today, we’ll talk about the “simplest” class of Qt, a class we use every day, a class we often do need to care about the details – QString.
Despite the fact that QString internally stores characters as wide chars(a character occupies 2 bytes to store its unicode), you can not initialize QString with wchar*. The following code is not correct:
QString a=L"abcd“; QString b(L"abcd");
You can only initialize QString with char*
QString a="abcd"; QString b("abcd");
Note that the terminal ‘\0’ in “abcd” is not copied to QString, which means QString is not null-terminated, which also means you can put ‘\0’ in middle of QString.
QString a="abcd"; a[2]='\0'; int len=a.length();//4
Although QString does not store the terminal ‘\0’ of “abcd”, you must provide a null-terminated char * to initialize QString. Otherwise, QString does not know how many bytes are copied to its internal memory.
But QString::data does add an additional QChar(‘\0’) to its returned QChar array. The QChar(‘\0’) is usually used to indicate the end of the QChar array if there is no ‘\0’ in middle of QString. So the reliable way to determine the end of the returned QChar array is not using the appended QChar(‘\0’) but using QString::length(). QString::data returns the address of its internal QChar array. You can use that to access or modify the data of the QString but you cannot write beyond the current size of the QChar array. Filling the terminating QChar(‘\0’) with NULL QChar won’t enlarge the internal memory and the size of QString remains unchanged. Writing beyond the current memory size may crash the app.
QString::toWCharArray(wchar_t*);
will copy the wchar characters stored in QString to its argument. Since QString is not null-terminated, there would be no ‘\0\0’ in the resulting wchar_t*.
QByteArray is like QString, which can contain the null byte in the middle. The length of QByteArray is not determined by the position of the null byte but QByteArray::length(). Like QString::data, QByteArray::data appends a ‘\0’ to the returned char array. You can use the returned pointer of QByteArray::data to access or modify the content of QByteArray.