I’m attempting to simplify my code with a function that generates an array of CGPoints and returns a pointer to the first element in this array.
CGPoint* getVerticesFromRect(const CGRect rect) {
CGPoint vertexArray[] =
{ ccp(rect.origin.x, rect.origin.y),
ccp(rect.origin.x + rect.size.width, rect.origin.y),
ccp(rect.origin.x + rect.size.width, rect.origin.y - rect.size.height),
ccp(rect.origin.x, rect.origin.y - rect.size.height) };
CGPoint *vertices = &vertexArray[0];
return vertices;
}
This work correctly, but the problem arises when I attempt to use this CGPoint* in:
void ccDrawPoly( const CGPoint *poli, NSUInteger numberOfPoints, BOOL closePolygon )
Like so:
void ccDrawRect( const CGRect rect ) {
CGPoint *vertices = getVerticesFromRect(rect);
// Makes an array from the pointed CGPoints
CGPoint vertexArray[] = {vertices[0], vertices[1], vertices[2], vertices[3]};
ccDrawPoly(vertexArray, 4, YES); // This works
ccDrawPoly(vertices, 4, YES); // This doesn't
}
I have found that attempting to read the *vertices variable in ccDrawRect gives the correct values, but I’m getting garbage values on the other side when passing it into ccDrawPoly. What’s the reason behind this? From what I know, CGPoint *poli and CGPoint poli[] should be identical. Is it the const that’s causing the issue?
EDIT
Following the advice here I changed my function and passing the pointer works fine now. The problem was returning a pointer to a local variable which didn’t stick around for long. Instead, I’ve used malloc and I free the memory in the caller function once it’s no longer needed.
CGPoint* getVerticesFromRect(const CGRect rect) {
CGPoint *vertices = (CGPoint*) malloc(sizeof(CGPoint) * 4);
assert(vertices);
vertices[0] = ccp(rect.origin.x, rect.origin.y);
vertices[1] = ccp(rect.origin.x + rect.size.width, rect.origin.y);
vertices[2] = ccp(rect.origin.x + rect.size.width, rect.origin.y - rect.size.height);
vertices[3] = ccp(rect.origin.x, rect.origin.y - rect.size.height);
return vertices;
}
void ccDrawRect( const CGRect rect ) {
CGPoint *vertices = getVerticesFromRect(rect);
ccDrawPoly(&vertices[0], 4, YES);
free(vertices);
vertices = NULL;
}
You’re using a local variable outside of its scope.
Instead of allocating array on stack as you do:
You need to use the
mallocfunction and create a dynamically allocated array. Don’t forget tofreeit of course.(Is it really C?)