【问题标题】:return reference to dynamically generated 2D array返回对动态生成的二维数组的引用
【发布时间】:2023-03-29 08:57:02
【问题描述】:
//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];
}

【问题讨论】:

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


    【解决方案1】:
    • 您应该分配指针大小而不是结构大小。
    • 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 中执行此操作。

    【讨论】:

    • 使用CGPointMake()没有问题,因为结构实例被分配到了合适的(堆)位置。事实上,CGPointMake() 是一个内联函数,除非程序是用-O0 构建的,否则根本不会分配堆栈。
    • 我不知道这一点,感谢您指出。我做了必要的调整。 :)
    猜你喜欢
    • 2014-06-27
    • 2017-08-16
    • 2020-01-14
    • 2019-01-12
    • 2011-04-25
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多