[Qt-interest] [Newbie question] Why string.toAscii().data() doesn't work?

Jesús Spí­nola jspinola at gmail.com
Thu Mar 26 12:10:59 CET 2009


I'll like to know why this code doesn't work:

QString testingString = "testing";
char *data = testingString .toAscii().data();
qDebug() << "data = " << data;
std::cout<<"data = " << data << std::endl;

It prints garbage on data. But if I do this way:

QString testingString = "testing";
QByteArray temp = testingString.toAscii();
char *data = temp.data();
qDebug() << "data = " << data;
std::cout<<"data = " << data << std::endl;

It prints "testing" correctly.

My explanation is that on the first version the pointer returned by data()
points to a temporally object "alive" only on the same line, so, when we
reach the next lines the memory of this pointer is invalid.

Is this correct? It doesn't feel natural to me coming from a C# world :P


-- 
Jesús Spínola
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090326/5c4118aa/attachment.html 


More information about the Qt-interest-old mailing list