tags:

views:

93

answers:

2

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 ?

A: 

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.nokia.com/latest/containers.html

leinir
Dynamically allocated arrays are certainly part of the C++ Standard.
anon
You are thinking about static arrays with size that is not compile-time computable. As Neil said, dynamically allocated arrays can have runtime determined size.
zarzych
You are of course entirely correct. i should know better than answering questions like this in an uncaffeinated state ;)
leinir
+3  A: 

Hello,

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 points;

points.resize(dx + 1);

You can also do:

QVector * points = new QVector(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.nokia.com/4.6/implicit-sharing.html#implicit-data-sharing

cnebrera
Alright, so after doing:int dx = 5;QVector points;points.resize(dx + 1);Can I just store each individual QPoint as:point[i] = new QPoint(1,1);??
Ahmad
Yes you can do that :). But if you want to store pointers then you have to declare the QVector like: QVector<QPoint*> points;
cnebrera
If you think this is the right answer please set is as correct answer, thanks!
cnebrera
Use RAW pointers is not good practice wrap it in a smart pointer
Martin York
Hi Martin, you are totally right it is always better to use smart pointers to avoid error. But you can also use normal pointers for performance if you are careful with them.
cnebrera