c++ - 返回对动态生成的二维数组的引用

标签 c++ objective-c c multidimensional-array malloc

//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) 在堆栈而不是堆中创建结构。 感谢@Bvarious 指出这不是真的。请参阅下面的评论。 :)

执行您想要的操作的代码:

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

警告:当您不再需要二维数组时,您必须记住释放它。一种方法是将其包装在 Obj-C 包装器中,并在 initdealloc 中执行此操作。

关于c++ - 返回对动态生成的二维数组的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5686134/

相关文章:

iphone - 如何在 iPhone 窗口应用程序中显示另一个窗口

c - Valgrind 无效读取

c - 线程 : how can you signal you're ready, 如果您仅在被阻止时才准备好?

c++ - 遇到无效写入问题

c++ - 树的常量和非常量版本的访问者模式

ios - AFNetworking - 不支持的 URL

c - 当按字符代替 int 时如何停止无限循环?

c++ - 在 Windows 7 下的 Qt 5.5.1 应用程序中使用 RInside

c++ - LLDB是如何实现设置断点功能的?

objective-c - 没有名为 'NSTableViewDataSource' 的类型或协议(protocol)