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()]; //此处有误
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]; //正确
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[]().
-------------------------------------------------------------------------------------------------------------------------------
//常用参数类型:char *字符串, QByteArray字符数组, QString字符串
1、char* -------------> QByteArray 使用构造函数 QByteArray(const char*)
char* str;
QByteArray byte(str); //QByteArray构造函数
2、char* -------------->QString 使用构造函数 QString(const char*)
char* str;
QString string(str); //QString构造函数
3、QByteArray ------>char* 使用成员函数 QByteArray::data()
QByteArray byte;
char* str = byte.data(); //QbyteArray::data()
4、QByteArray ------>QString 使用构造函数 QString(const QByteArray &ba)
QByteArray byte;
QString string(byte); //QString构造函数
5、QString ----------> QByteArray 使用成员函数 QString::toAscii()
QString string;
QByteArray byte = string.toAscii(); //QString::toAscii
6、QString ------------>char* 使用 qPrintable()
QString string;
char* str = qPrintable(string);
7、QString ------------->string
QString qstr;
string str = qstr.toStdString();
8、string ---------------->QString
string str;
QString qstr = QString::fromStdString(str);