char *QByteArray::data()
Returns a pointer to the data stored in the byte array. The pointer can be used to access and modify the bytes that compose the array. The data is '\0'-terminated, i.e. the number of bytes in the returned character string is size() + 1 for the '\0' terminator.
Example:
QByteArray ba("Hello world");
char *data = ba.data();
while (*data) {
cout << "[" << *data << "]" << endl;
++data;
}
The pointer remains valid as long as the byte array isn't reallocated or destroyed. For read-only access, constData() is faster because it never causes a deep copy to occur.
This function is mostly useful to pass a byte array to a function that accepts a const char *.
The following example makes a copy of the char* returned by data(), but it will corrupt the heap and cause a crash because it does not allocate a byte for the '\0' at the end:
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size()]; // wrong here
strcpy(data, text.data());
delete [] data;
This one allocates the correct amount of space:
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size() + 1]; //correct
strcpy(data, text.data());
delete [] data;
Note: A QByteArray can store any byte values including '\0's, but most functions that take char * arguments assume that the data ends at the first '\0' they encounter.
See also constData() and operator[]().
-------------------------------------------------------------------------------------------------------------------------------
//Common parameter types: char * string, QByteArray character array, QString string
1. char* -------------> QByteArray uses the constructor QByteArray(const char*)
char* str;QByteArray byte(str); //QByteArray constructor
2. char* -------------->QString uses the constructor QString(const char*)
char* str;
QString string(str); //QString constructor
3、QByteArray ------>char* 使用成员函数 QByteArray::data()
QByteArray byte;
char* str = byte.data(); //QbyteArray::data()
4. QByteArray ------> QString uses the constructor QString(const QByteArray & ba )
QByteArray byte;
QString string(byte); //QString constructor
5、QString ----------> QByteArray 使用成员函数 QString::toAscii()
QString string;
QByteArray byte = string.toAscii(); //QString::toAscii
6、QString ------------>char* 使用 qPrintable()
QString string;
char* str = qPrintable(string);