开发者

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开发者_JS百科 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜