开发者

return reference to dynamically generated 2D array

//header file

CGPoint **positions;

//Implementation file
int rows = 10;
int columns = 6;

positions = malloc(rows * sizeof(CGPoint));

for(int i=0; i<rows; i++){
    positions[i] = malloc(columns * sizeof(CGPoint));
}

positions[0][0] = CGPointMake(682, 0);
positions[0][1] = CGPointMake(682, 336);
positions[0][2] = CGPointMake(0, 0);
positions[0][3] = CGPointMake(-341, 336);
positions[0][4] = CGPointMake(0, 336);
positions[0][5] = CGPointMake(341, 0);

positions[1][0] = CGPointMake(341, 0);
positions开发者_如何学Python[1][1] = CGPointMake(341, 336);
positions[1][2] = CGPointMake(682, 336);
positions[1][3] = CGPointMake(-341, 336);
positions[1][4] = CGPointMake(0, 336);
positions[1][5] = CGPointMake(0, 0);

//and so on..

I need help on writing following function that will return a random 2nd dimension of positions like this. returning complete subarray positions[0] or positions[1],

- (CGPoint *)point {
    return positions[arc4random() % rows];
}


  • You should allocate pointer size rather than structure size.
  • CGPointMake(x, y) create the structure in stack rather than heap. Thanks @Bavarious for pointing out that that this is not true. See comment below. :)

The code to do what you want:

unsigned int row = 10;
unsigned int column = 10;
CGPoint **points = malloc(row * sizeof(CGPoint *));
for (int r = 0; r < row; ++r) {
    points[r] = malloc(column * sizeof(CGPoint));
    for (int c = 0; c < column; ++c) {
        points[r][c].x = 0.0;
        points[r][c].y = 0.0;
    }
}

WARNING: You have to remember to free 2D array when you do not need it anymore. One way is to wrap it in Obj-C wrapper and do that in your init and dealloc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜