返回对动态生成的二维数组的引用
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..
我需要帮助编写以下函数,将返回像这样的位置的随机第二维。返回完整的子数组位置[0]或位置[1],
- (CGPoint *)point {
return positions[arc4random() % rows];
}
- 你应该分配指针大小而不是结构大小。
CGPointMake(x, y)
在堆栈而不是堆中创建结构。
做你想做的事的代码:
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包装器中,并在init
和dealloc
中这样做。
相关文章:
- 将值从二维数组输出到文本文件
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- 如何正确填充在堆上分配的二维数组?
- 传递二维数组时出现问题
- 具有随机数的二维数组不会更改
- 如何在C++中获取二维数组中最少的一列数?
- 如何使用用户输入变量制作二维数组?
- C++ 中动态二维数组的访问冲突
- 遍历二维数组的所有子数组
- 将二维数组的所有元素插入到一维数组中
- 在函数中传递二维数组
- 为什么我需要三个嵌套的大括号来调用赋值运算符,将const引用到二维数组
- C++ 二维数组和指针引用
- 如何使用一个动态创建的一维数组的二维数组引用仅与标准库?
- 如何在二维数组中引用对象
- 如何在c++中发送一个二维数组作为引用,并返回
- 在函数搜索模式中引用二维数组时出错
- c++中二维数组中引用传递的问题
- 返回对动态生成的二维数组的引用