PDA

View Full Version : QString to char *



barrygp
4th September 2009, 19:21
Why does the first assignment not work in the section of code below.. does not seem to matter whether to8bit is used as well or not.. However, works when you pass it through a string class.

Does not work:
QString s = QString(tr("whatever"));

const char * asdfasdf = s.toAscii().data();


qDebug(asdfasdf);

---------------
Works:

QString s = QString(tr("whatever"));

std::string str = std::string(s.toAscii().data());
const char * asdfasdf = str.c_str();


qDebug(asdfasdf);

wysota
4th September 2009, 19:59
const char * asdfasdf = s.toAscii().data();
Left: const char *
Right: char *


const char * asdfasdf = str.c_str();
Left: const char *
Right: const char *

See the difference?


QString s;
const char *xyz = s.toAscii().constData();

By the way, all these assignments can lead to a crash.

You can try this:

QString s;
QByteArray ba = s.toAscii();
const char *xyz = ba.constData(); // as long as ba exists, xyz will be valid

zhnde
4th September 2009, 19:59
Why does the first assignment not work in the section of code below.. does not seem to matter whether to8bit is used as well or not.. However, works when you pass it through a string class.

Does not work:
QString s = QString(tr("whatever"));

const char * asdfasdf = s.toAscii().data();


qDebug(asdfasdf);

---------------
Works:

QString s = QString(tr("whatever"));

std::string str = std::string(s.toAscii().data());
const char * asdfasdf = str.c_str();


qDebug(asdfasdf);


s.toAscii() create a interim variable that will be released before qDebug(asdfasdf).

try qDebug(s.toAscii().data());

It must work.

zhnde
4th September 2009, 20:02
---------------
Works:

QString s = QString(tr("whatever"));

std::string str = std::string(s.toAscii().data());
const char * asdfasdf = str.c_str();


qDebug(asdfasdf);

here you have created a std::string str and asdfasdf = str.c_str() is available at qDebug(asdfasdf).