Reputation: 1358
I'm using a CvPoint
structure in OpenCV and I need to assign a value to x
and y
fields of the structure.
Here is my code:
CvPoint* P1;
P2[0].x=32;
But the programs always block while trying to set the value.
Any idea about how to set these values?
Upvotes: 1
Views: 18548
Reputation: 2984
no dynamic method:
CvPoint P1;
P1.x=32;
P1.y=32;
//////////////
CvPoint P2[2];
P2[0].x=32;
P2[0].y=32;
Upvotes: 3
Reputation: 1721
Well first of all P1 is a pointer to an object of type P1. In order to assign something to an object's member via its pointer you need to use the -> operator. If this pointer points to the beginning of an array you use the operator[] to access individual elements. This operator returns a reference for the given index, in this case CvPoint& .
1. dynamic allocation of a single object
CvPoint* P1 = new CvPoint(); // default construction of an object of type CvPoint
P1->x = 32;
// do something with P1
// clean up
delete P1;
2. dynamic allocation or an array
CvPoint* points = new CvPoint[2]; // array of two CvPoints
points[0].x = 32; // operator[] returns a reference to the CvPoint at the given index
points[1].x = 32;
// do something with points
// clean up
delete[] points;
Since in both examples the new operator has been used, it is mandatory to pair them with a matching call to delete or delete[] in case of an array.
Upvotes: 4