How to allocate an array of pointers to a struct
I am using the CvPoint2D32f struct of opencv, which is defined as
typedef struct CvPoint2D32f
{
float x; /* x-coordinate, usually zero-based */
float y; /* y-coordinate, usually zero-based */
}
CvPoint2D32f;
I am trying to allocate an array of pointers of these objects as follows, and it is not working. How is this to be accomplished?
CvPoint2D32f *cvpoints[8];
for (i = 0; i < 16; i++)
{
if (i % 2 == 0)
{
(*cvpoints)[i/2].x = float(points[i]); // points is an array of ints.
}
else
{
(*cvpoints)[i/2].y = float(points[i]);
开发者_如何学Python }
}
You have an array of pointers to CvPoint2D32f
, not an array of the structs themselves. You have no memory allocated for the actual structures. You have three options:
- Change your declaration to
CvPoint2D32f cvpoints[8];
so you have all of the structures in an array on the stack. After you allocate the array for the pointers, add a malloc statement to allocate memory. Example:
CvPoint2D32f *cvpoints[8]; for (i = 0; i < 8; i++) { cvpoints[i] = (CvPoint2D32f *)malloc(sizeof(CvPoint2D32f)); }
Use
malloc
to allocate size for all the structures. Example:CvPoint2D32f *cvpoints = (CvPoint2D32f *)malloc( 8 * sizeof(CvPoint2D32f));
CvPoint2D32f *cvpoints = (CvPoint2D32f*) malloc(sizeof(struct CvPoint2D32f) * 8);
memset(cvpoints, \0, sizeof(struct CvPoint2D32f) * 8);
for (i = 0; i < 16; i++)
{
if (i % 2 == 0)
{
cvpoints[i/2].x = float(points[i]); // points is an array of ints.
}
else
{
cvpoints[i/2].y = float(points[i]);
}
}
And when you're done with them, you free the memory:
free(cvpoints);
Where do these pointers point to? I guess what you want to do is allocate dynamic memory for the structs, but I don't see any memory allocation in your code. Currently all pointers point to undefined memory, so of course this will fail.
You are just creating the pointers, but you need them to point to something in memory!
Example:
struct CvPoint2D32f *cvpoint = (struct CvPoint2D32f *)malloc(sizeof(struct CvPoint2D32f));
if (cvpoint == NULL) {
//malloc error
}
精彩评论