Access C Array within blocks (variable array count) Objective-C

user207616 picture user207616 · Mar 28, 2011 · Viewed 8k times · Source

Blocks are fine but what about writing C arrays?

Given this simplified situation:

CGPoint points[10];
[myArray forEachElementWithBlock:^(int idx) {
    points[idx] = CGPointMake(10, 20); // error here
    // Cannot refer to declaration with an array type inside block
}];

after searching a while found this possible solution, to put it in a struct:

__block struct {
    CGPoint points[100];
} pointStruct;

[myArray forEachElementWithBlock:^(int idx) {
    pointStruct.points[idx] = CGPointMake(10, 20);
}];

this would work but there is a little limitation I have to create the c array dynamically:

int count = [str countOccurencesOfString:@";"];
__block struct {
    CGPoint points[count]; // error here
    // Fields must have a constant size: 'variable length array in structure' extension will never be supported
} pointStruct;

How can I access my CGPoint array within a block?

OR

Is it even possible at all or do I have to rewrite the block method to get the full functionality?

Answer

cefstat picture cefstat · Jun 22, 2011

Another simple answer which works for me is the following:

CGPoint points[10], *pointsPtr;
pointsPtr = points;
[myArray forEachElementWithBlock:^(int idx) {
    pointsPtr[idx] = CGPointMake(10, 20);
}];