[solved] constructing c-string-array (const char * []) from qstringlist



  • @
    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.


  • Lifetime Qt Champion

    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)



  • 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.



  • 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 :)



  • 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'.



  • 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!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.