传递CGPoint *而不是CGPoint []无效?

时间:2011-12-31 12:29:39

标签: ios arrays opengl-es cocos2d-iphone

我正在尝试使用生成CGPoints数组的函数来简化我的代码,并返回指向此数组中第一个元素的指针。

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

这项工作正常,但当我尝试在以下位置使用此CGPoint *时出现问题:

void ccDrawPoly( const CGPoint *poli, NSUInteger numberOfPoints, BOOL closePolygon )

像这样:

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
}

我发现尝试阅读*vertices中的ccDrawRect变量会给出正确的值,但是当我将其传递给ccDrawPoly时,我会在另一端获得垃圾值。这背后的原因是什么?据我所知,CGPoint * poli和CGPoint poli []应该是相同的。这是导致问题的const吗?

修改

遵循建议here我改变了我的功能并且传递指针现在工作正常。问题是返回一个指向局部变量的指针,该变量没有长时间停留。相反,我已经使用了malloc,并且一旦不再需要,我就会释放调用函数中的内存。

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

1 个答案:

答案 0 :(得分:3)

您正在使用其范围之外的局部变量。

而不是像你一样在堆栈上分配数组:

CGPoint vertexArray[] = ...

您需要使用malloc函数并创建动态分配的数组。当然不要忘记free

(它真的是C?)