[Qt-interest] howto convert QString to char*

Thiago Macieira thiago at kde.org
Tue Jul 13 20:42:07 CEST 2010


On Tuesday 13. July 2010 20.02.26 Gabriel M. Beddingfield wrote:
> On Tue, 13 Jul 2010, Matthias Pospiech wrote:
> >>> I am using the following:
> >>>     char * toChar(const QString str)
> >>>     {
> >>>     
> >>>         QByteArray ba = str.toLatin1();
> >>>         return  ba.data();
> >>>     
> >>>     }
> >>> 
> >>> the bytearray contains usefull data,
> >>> however the value returned by data() is very useless.
> 
> I was curious, so I set up a simple test here.  With Qt
> 4.5.3, your toChar() works fine... as does the two that I
> proposed.

No, it doesn't work properly. It just looks like it does.

You're returning a pointer that gets deallocated before the function returns. 
If it works, it's just because the memory address didn't get reallocated for 
other purposes. But that makes it no less wrong: it's still a dangling pointer 
you're dereferencing.

> Maybe there's something else going on... like the original
> string changing unexpectedly?

The only thing that can work is a macro. That's what qPrintable is. And you 
still must not save the pointer anywhere...

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Senior Product Manager - Nokia, Qt Development Frameworks
      PGP/GPG: 0x6EF45358; fingerprint:
      E067 918B B660 DBD1 105C  966C 33F5 F005 6EF4 5358
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 190 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20100713/083c74cf/attachment.bin 


More information about the Qt-interest-old mailing list