Is their any way I can convert QString to char ??
Thanks in advance,
Boss
Is their any way I can convert QString to char ??
Thanks in advance,
Boss
You can't convert whole string to a single character. What exactly are you trying to do?
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.Originally Posted by momesana
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:
Qt Code:
char * ch_str = qstrdup(qPrintable(str));To copy to clipboard, switch view to plain text mode
Well, I don't think so!Originally Posted by wysota
I am not an experienced C++ programmer but I doubt that the code above will cause any problems.
Try this
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 .Qt Code:
const char * ch_str; { // Block of code 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 errorTo copy to clipboard, switch view to plain text mode
Thanx in advance
momesana
Last edited by momesana; 20th July 2006 at 12:37.
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.Originally Posted by momesana
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.Originally Posted by momesana
seems like I have a lot of code to rewrite then
Bookmarks