[Qt-interest] howto convert QString to char*

Konrad Rosenbaum konrad at silmor.de
Wed Jul 14 13:36:14 CEST 2010


On Wed, July 14, 2010 09:58, Mandeep Sandhu wrote:
>> Or perhaps:
>>
>> #define toChar(x) ((x).toLatin1().data())
>
> Is this guaranteed to work? As in the QByteArray created here is only
> temporary, so it ceases to exist after this statement?

This is guaranteed to work for any valid x that is of type QString. With
the cautionary warning that it works exactly up to the semicolon following
your use of "toChar(x)".

Example that works:

QString my="Hello World";
printf("%s\n",toChar(my));

Example that DOES NOT work:

QString my="Hello World";
char*cs=toChar(my);
printf("%s\n",cs);

I hope you can spot the difference!

> I usually keep the QByteArray around as long as I need the "char *".
> I've experienced some strange results while using this single line
> (sometime I used to get garbage in the char pointer).

That is exactly the difference between the two examples above: if you have
a semicolon between your call of "toChar" and your use of the pointer then
your pointer is invalid - it just sometimes happen to point to a location
that was not overwritten yet.

If you need the pointer to continue to stay valid you must keep the
QByteArray around. Even then: if you make ANY change to the array, the
pointer becomes invalid - so I would recommend to not remember the pointer
at all, but to use QByteArray::data() every time you need it. You should
also make sure that the code you are calling with that pointer does not
remember the pointer after being done with it and does not do anything
funky with it (ie. trying to de- or re-allocate it).


    Konrad




More information about the Qt-interest-old mailing list