簡體   English   中英

返回對動態生成的2D數組的引用

[英]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[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..

我需要編寫以下函數的幫助,該函數將返回像這樣的位置的隨機第二維。 返回完整的子數組position [0]或positions [1],

- (CGPoint *)point {
    return positions[arc4random() % rows];
}
  • 您應該分配指針大小而不是結構大小。
  • CGPointMake(x, y)在堆棧而不是堆中創建結構。 感謝@Bavarious指出這不是事實。 請參閱下面的評論。 :)

執行您想要的代碼:

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

警告:您必須記住在不再需要2D數組時將其釋放。 一種方法是將其包裝在Obj-C包裝器中,然后在initdealloc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM