[SOLVED] QString to const char *
my code is like this :
const char * mytext= textBox.text().toUtf8().constData();
QString mystring = QString::fromUtf8(mytext);
now mystring just equals "Q" .
Should it not be "QWERTY" ?
What am I doing wrong ?
More to the point , I am using a 3rd party function that takes const char * as argument .
I only have the function interface not the implementation .
When I try to get a QString from the QLineEdit and convert it to const char * and feed it to the 3rd party function , the function fails to give proper output .
When I just feed the equivalent string literal to the function , the function gives correct output .
So something is wrong with the .toUtf8().constData() conversion from QString to const char * .
I think .
I think this code of your's is flawed:
@const char * mytext = textBox.text().toUtf8().constData();@
The toUtf8() function returns a QByteArray object containing the UTF8-converted string. And constData() returns a pointer to that QByteArray's internal buffer. But you don't keep the QByteArray object anywhere! So the temporary QByteArray is destroyed instantly - thus your pointer is dangling!
Try instead one of those:
@// --- Method #1 ---
const QByteArray byteArray = mytext = textBox.text().toUtf8();
const char *mytext = byteArray.constData();
// --- Method #2 ---
const char *mytext = strdup(textBox.text().toUtf8().constData());@
Don't forget free(mytest), if you use method #2 ;-)
From the docs:
[quote]const char * QByteArray::constData () const
Returns a pointer to the data stored in the byte array. The pointer can be used to access the bytes that compose the array. The data is '\0'-terminated unless the QByteArray object was created from raw data. The pointer remains valid as long as the byte array isn't reallocated or destroyed.[/quote]
Thank you for explaining that . I tried your method 1 and it works .