CGPoint阵列中的索引从i + 1开始?

时间:2012-07-02 04:36:22

标签: arrays cocos2d-iphone indexing

有人知道为什么我从来没有得到我阵列的第一个值吗?它总是从索引i + 1开始,当我在0开始for循环时,或者像在这里1:而不是x = 44,控制台说x = 100:

//at the top
#define kMaxHillKeyPoints 5

//in the .h:
CGPoint _hillKeyPoints[kMaxHillKeyPoints];

- (void)generatePath {

    int _nVertices = 1;

    _hillKeyPoints[_nVertices] = CGPointMake(44, 0);
    _hillKeyPoints[_nVertices++] = CGPointMake(100, 75);
    _hillKeyPoints[_nVertices++] = CGPointMake(50, 150);
    _hillKeyPoints[_nVertices++] = CGPointMake(150, 225);

    for(int i = 1; i < 4; i++) {   
        CCLOG(@" _hillKeyPoints[1].x : %f", _hillKeyPoints[1].x);
        CCLOG(@"%i", i);
    }
}

//output :
_hillKeyPoints[1].x : 100.000000 //why not x = 44 ?
你知道为什么吗?我也清理了项目,但它没有改变任何东西。

由于

1 个答案:

答案 0 :(得分:2)

首先,您执行了以下操作:

int _nVertices = 1;
_hillKeyPoints[_nVertices] = CGPointMake(44, 0); //_nVertices = 1

这将_hillKeyPoints [1]分配给(44,4)。在这里,你仍然很好(你可以在这里验证NSLog)。

但是,在以下声明中:

_hillKeyPoints[_nVertices++] = CGPointMake(100, 75);

后递增 _nVertices。这意味着_hillKeyPoints [_nVertices]首先被分配给(100,75),然后值_nVertices被递增。上面的陈述完全等同于这样做:

_hillKeyPoints[_nVertices] = CGPointMake(100, 75); 
_nVertices = _nVertices + 1;

请注意,在赋值期间_nVertices = 1,因此您将覆盖先前的(44,0)赋值,因此最终得到_hillKeyPoints [1] =(100,75)。

如果您仍然希望按照自己的方式进行操作,则每次都可以预先增加索引:

int _nVertices = 1; 
_hillKeyPoints[_nVertices] = CGPointMake(44, 0); //_nVertices = 1
_hillKeyPoints[++_nVertices] = CGPointMake(100, 75); //_nVertices = 2
_hillKeyPoints[++_nVertices] = CGPointMake(50, 150); //_nVertices = 3
_hillKeyPoints[++_nVertices] = CGPointMake(150, 225); //_nVertices = 4

希望这有帮助。