关闭

QString unsigned char* 的转换

标签: deletenullc
1618人阅读 评论(0) 收藏 举报
分类:
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!


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:82194次
    • 积分:1457
    • 等级:
    • 排名:千里之外
    • 原创:41篇
    • 转载:86篇
    • 译文:0篇
    • 评论:3条
    文章分类
    最新评论