Solved can not print correctly after convert QString to char *
-
Yes! I's just luck that the bits are still around in Release mode. The Debug mode output of ??????? could happen in Release also some other day when the sun doesn't shin.e
Anyway, one simple modification to make it waterproof could be:
QString s = "hello world"; qDebug() << s; qDebug() << s.toUtf8().data(); QByteArray a = s.toUtf8(); char* p = a.data(); qDebug() << p; QByteArray b = s.toUtf8(); p = b.data(); qDebug() << p;
Edit: too fast, didn't read the code in the 3d paragraph ! But they are both waterproof now :-)
-
@hskoglund
that is interesting .
i dont have test on linux or MinGW, maybe vs and MinGW is diffrent on deal with temp object? -
@Mozzie Actually MinGW works on Windows as well (I prefer it over MSVC2017 because MinGW compiles/builds my projects faster).
-
@Mozzie said in can not print correctly after convert QString to char *:
where is the temp object in memory, stack or heap or somewhere else.
It's on the stack since you did not allocate it with new
if it is on stack, it can not remain until the stack is finished
No, this is not allowed since it's unnamed.
It's also not c++ specific - you can do the same (in a little bit more obvious way) in C:
int *myPtr = nullptr; { int a = 3; myPtr = &a; printf("%d\n", *myPtr); // works fine } printf("%d\n", *myPtr); // works on garbage and may eat kitten
-
@Christian-Ehrlicher said in can not print correctly after convert QString to char *:
int *myPtr = nullptr;
Never heard of
nullptr
in C ;-)NULL
was much nicer to read anyway. -
This post is deleted! -
@Christian-Ehrlicher
thanks, it helped a lot.
and i have a hunch{//main stack QString s = "hello world"; char* p = nullptr; {// toUtf8() QByteArray b = s.toUtf8(); {// data(); p = b.data(); qDebug() << p; // does this is same as "qDebug() << s.toUtf8().data();" } } // b is freed qDebug() << p; // this is same as "char * p = s.toUtf8().data(); qDebug() << p;" }
does this right?
-
@JonB
nullptr is a c++11 key word, you can still use NULL, but NULL is defined as 0, sometimes it may cause some problem.such as:
void test(int *p) { qDebug() << "int *"; } void test(int i) { qDebug() << "int"; } test(NULL); test(nullptr);
output
int int *
-
@Mozzie
I know this :) That's why I was picking @Christian-Ehrlicher on his use ofnullptr
in his C program, it was just intended for amusement ;-) -
@Mozzie said in can not print correctly after convert QString to char *:
does this right?
Yes, exactly.
-
@Christian-Ehrlicher
thanks.