简体   繁体   中英

How do I dynamically allocate memory for arrays in Qt C++?

I'm having some issues in allocating memory for an array dynamically in C++ within Qt SDK ... Here's for I'm doing:

int dx = 5;
QPoint * qPoint;
qPoint = new QPoint[dx+1];

However when I try to debug the code, the programs just crashes when it tries to execute the third line .... any clues ?

If you want to use Qt SDK properly you have to use QVector instead of C++ arrays or std arrays. You can use QVector as a pointer or not, it doesn't really matter since internally it will allocate the memory dynamically.

For example:

int dx = 5;

QVector<QPoint> points;

points.resize(dx + 1);

You can also do:

QVector<QPoint> * points = new QVector<QPoint>(dx + 1);

In case you want the vector as a pointer. But Qt uses implicit memory sharing for vectors so you can use the first approach most of the times.

http://doc.qt.io/qt-5/implicit-sharing.html#implicit-data-sharing

You seem to be doing something which is specifically stated in the C++ standard is not supposed to be done (dynamic arrays) :) In the case of Qt, what you likely want to do is to use a QList. See also the Qt documentation about generic containers: http://doc.qt.io/qt-5/containers.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM