PDA

View Full Version : QString to char



boss_bhat
19th July 2006, 13:49
Is their any way I can convert QString to char ??

Thanks in advance,
Boss

jacek
19th July 2006, 14:12
You can't convert whole string to a single character. What exactly are you trying to do?

momesana
19th July 2006, 14:34
something like that should work ...

QString str = "Qt4 rocks!";
const char* ch_str = str.toStdString().c_str();

std::cout << "converting QStrings to chars: " << ch_str << std::endl;

wysota
19th July 2006, 16:38
something like that should work ...

QString str = "Qt4 rocks!";
const char* ch_str = str.toStdString().c_str();

std::cout << "converting QStrings to chars: " << ch_str << std::endl;

Uuuuu.... this is a snippet which can cause a beautiful segmentation fault.

std::string here will be a temporary object, so it'll get invalid as soon as c_str() returns, causing an invalid pointer to be assigned to ch_str and a potential memory access error to occur when you try to access it at some later point in time.

Try this instead:

QString str = "Qt4 rocks!";
char * ch_str = qstrdup(qPrintable(str));

momesana
20th July 2006, 12:31
Uuuuu.... this is a snippet which can cause a beautiful segmentation fault.

Well, I don't think so!
I am not an experienced C++ programmer but I doubt that the code above will cause any problems.
Try this



const char * ch_str;
{ // Block of code
QString str = "Qt4 rocks!";
ch_str = str.toStdString().c_str();
} // End of block of code. All local variables in the block cease to exist
std::cout << ch_str << std::endl;
// std::cout << str.toStdString() << std::endl; // That would cause an error

Printing str.toStdString() would cause an error since the variable went out of scope and died, the value it refered to however, still exists (as proven by the above print statement). Correct me if I am wrong. As I said, I am not a C++ expert :).

Thanx in advance
momesana

jacek
20th July 2006, 12:38
as proven by the above print statement
It doesn't work --- it "works". Because memory where ch_str points to wasn't overwritten yet, you can read it, but it will crash someday.

wysota
20th July 2006, 16:58
...(as proven by the above print statement)...
It's not a proof, it's plain luck. The fact that something works once doesn't mean it works. The fact that something doesn't work once means it doesn't work. If you assign the value as you did and then allocate all the memory available in your system, then set it all to zeroes, deallocate and then try to print that variable, you'll get nothing. Furthermore it's enough to test your example code using some memory debugger like Valgrind, I'm sure it'll report a warning in the line where you try to access the variable.

momesana
20th July 2006, 23:26
seems like I have a lot of code to rewrite then :(