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

Jesús Fernández jsfdez at gmail.com
Thu Mar 26 12:20:26 CET 2009


Yes, It is :)

The char array in first case only exists in the call line.

The second case stores the data in a QByteArray, if you do:
std::cout<<"data = " << testingString .toAscii().data() << std::endl;
will work

2009/3/26 Jesús Spí­nola <jspinola at gmail.com>

> 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
>
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-interest
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090326/79b0d635/attachment.html 


More information about the Qt-interest-old mailing list