CDT
CDT

Reputation: 10631

convertion from QString to char pointer generates empty string

Here's some test code:

QString qstr_test("TEST");
const char *p = qstr_test.toStdString().c_str();
cout << p << endl;

Nothing is output as p is an empty string.

Here's what I got at debugging:

std::basic_string<char,std::char_traits<char>,std::allocator<char> >::c_str 
returns:    0x003bf9d4 "TEST"   

p      :    0x003bf9d4 ""

It seems p is pointing to the right location but doesn't display the right content.

Why is p empty ?

Upvotes: 1

Views: 926

Answers (1)

Pavel Strakhov
Pavel Strakhov

Reputation: 40502

std::string object is temporary and is destroyed right after c_str() is completed. But std::string owns char* buffer returned by c_str() and this buffer is also destroyed. So your code is incorrect and dangerous. You need to store std::string as long as you use char* buffer:

std::string s = qstr_test.toStdString();
const char* p = s.c_str();

Also it seems pointless to create std::string just to convert it to char*. QString has better methods: toLatin1, toLocal8bit, and toUtf8. Note that returned QByteArray has the same issue that is a common source of mistakes. QByteArray also must be stored if you want to use its buffer.

QByteArray array = qstr_test.toUtf8();
const char* p = array.constData();

I think this method is better because here you specify explicitly the encoding you need to use. And toStdString result depends on QTextCodec::codecForCStrings() current value.

Upvotes: 5

Related Questions