Qt World Summit: Submit your Presentation

Error: array initializer must be an initializer list or string literal

  • when I try to do this:

    @char string1[] = str;
    //str is a QString@

    I get this error

    @error: array initializer must be an initializer list or string literal@

    What can I do to fix this?

  • A QString cannot be casted into a char array, have a look at the doc. You can for instance use

    char string1[] = str.toStdString().c_str();
    char string1[] = str.unicode();

    IIRC depending on your Qt version, the first solution won't work. Note also that depending on your encoding (latin1, utf8, ...) you may need to set the codec for the char array to contain what you expect.

  • It is discouraged to use C-style static arrays in C++; the code you wrote will probably not compile because of not specifying an array size beforehand.

    Instead of going this way, have a look at "C++ std::string":http://www.cplusplus.com/reference/string/string/ or better yet, since you're dabbling in Qt, stick to "QStrings":http://qt-project.org/doc/qt-5.0/qtcore/qstring.html when wanting to represent textual data of any kind and to "QByteArrays":http://qt-project.org/doc/qt-5.0/qtcore/qbytearray.html when wanting to represent "lower-level" data (bytes, flags, et cetera).

    @#include <QByteArray>
    #include <QDebug>
    #include <QString>

    int main()
    QString string = QString::fromUtf8("This is a test QString variable. ½ ¼ ¾ ⅓ ⅔ † ‡ µ ¢ £ €");
    QByteArray array = string.toUtf8();

    qDebug() << string;
    qDebug() << array;


Log in to reply