[solved] constructing c-string-array (const char * []) from qstringlist
-
wrote on 26 Jun 2013, 14:05 last edited by
@
int i =0;
QStringList list;
list << "uno" << "dos" << "tres";
int size = list.size();
const char *c[size];
foreach(QString s, list)
{
c[i] = s.toLocal8Bit().constData();
i++;
}cout << endl << "print c-string-array" << endl; i = 0; while( i < size) cout << c[i++] << endl;
@
Returns three times tres. Tried using QString::const_iterator or QString[] to no avail.
Id be glad if someone could enlighten me on what is going on. -
Hi,
Check the value of the pointers in c, I wouldn't be surprised that it points to the same address (I haven't tested it, no Linux at hand)
-
wrote on 27 Jun 2013, 01:09 last edited by
Please note that, in following line
@
c[i] = s.toLocal8Bit().constData();
@you get a wild pointer saved in you c[i]. First, a temp QByteArray was created by toLocal8Bit. Then a pointer was got from the QByteArray. Finially, you destroy the QByteArray just after the assignment.
-
wrote on 27 Jun 2013, 18:00 last edited by
Ah, ok!
So copying data from temp QByteArray makes it persistent.
I replaced
@ c[i] = s.toLocal8Bit().constData(); @with
@ c[i] = new char[s.toLocal8Bit().size()];
strcpy(c[i],s.toLocal8Bit().constData()); @And removed const from c.
Thanks for bringing me on the right track :) -
wrote on 28 Jun 2013, 01:21 last edited by
OK, but note that,
For C-string char*, the data should be '\0'-terminated, which means the memory space needed should be string of length + 1.
And normally, for a QByteArray, it can contain '\0' char at any place, and may be not terminated with a '\0'.
-
wrote on 28 Jun 2013, 09:01 last edited by
In this example the strings are null-terminated though.
So in general you mean I should be using something like
@
c[i] = new char[s.toLocal8Bit().size()+1];
strcpy(c[i],s.toLocal8Bit().constData());
c[strlen(s[i])] = '\0';
@Anyhow thanks again for the hint, ill be '\0'-aware!
6/6