I have this structure:
typedef struct {
QPolygon polygon;
QRect position;
} form;
I try to initialize forms like below but I got segmentation fault error:
int n = 10
forms = (form*) malloc(sizeof(form) * n);
while (n>0) {
forms[n].position.setRect(0,0,0,0);
forms[n].polygon=QPolygon(0); //error - segmentation fault
forms[n].polygon = QPolygon(QRect(x, y, w, h)); //error - segmentation fault
}
I try like this also:
QPolygon v;
v = QPolygon(QRect(x, y, w, h)); //ok
v = QPolygon(QRect(x, y, w, h)); //ok
sprites[n].polygon = QPolygon(QRect(x, y, w, h)); //error - segmentation fault
How can I have a polygone into a struct?
First, define your struct like this in C++:
At the end of this answer there is a more modern alternative, but first, to directly fix your 20 years old style C++, write your code like this (you shouldn't, but just so you know how to do it):
For this, lets assume you have
Then you could make your code not crash, if you wrote it like this:
Your error might have been, because your
QPolygonandQRectinstances insideformstructs were not properly constructed. Hard to say, what you did was undefined behavior, accessing uninitialized memory like that. Additionally, you hadn==10in your loop's first iteration, which is outside valid index range 0..9, that might have crashed too.Additionally, when you allocate an array with
new, you must also delete it as array, so that array elements get properly destructed:With modern C++, you wouldn't need to do this, you'd use value types or smart pointers.
Finally, a more modern version, which is just all around easier and safer, and you don't need to worry about releasing memory, etc: