QString unsigned char* 的转换

来源:互联网 发布:网络问卷调查兼职 编辑:程序博客网 时间:2024/05/20 17:42
QString -> unsigned char* :
QString str = "ABCD";
 int length = str.length();
unsigned char* sequence = NULL;
sequence =(unsigned char*)qstrdup(str.toAscii().constData());
delete[] sequence;
- sequence length = 5 --> ['A'] ['B'] ['C'] ['D'] ['/0']
- sequence is now "independant" from str
- sequence has to be deleted with -> delete [] sequence

QString -> char:
const QByteArray ba = string.toAscii(); // make ba const, because modifying this array might otherwise invalidate the pointer
const char* sequence = ba.constData(); // now sequence will remain valid within the current scope.

The call to toAscii() creates a temporary QByteArray which goes out of scope when used like this:
char *sequence = string.toAscii().constData();
// sequence is now a dangling pointer!


原创粉丝点击