首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在块内访问C数组(变量数组计数) Objective-C

在块内访问C数组(变量数组计数) Objective-C
EN

Stack Overflow用户
提问于 2011-03-28 14:55:32
回答 2查看 8.4K关注 0票数 19

代码块很好,但是如何编写C数组呢?

考虑到这种简化的情况:

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

在搜索了一段时间后,找到了这个可能的解决方案,将其放在一个结构中:

代码语言:javascript
复制
__block struct {
    CGPoint points[100];
} pointStruct;

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

这是可行的,但有一点限制,我必须动态创建c数组:

代码语言:javascript
复制
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;

如何在block中访问我的CGPoint数组?

这有可能吗?或者我必须重写block方法才能获得完整的功能吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-03-28 15:14:18

也许你可以在堆上分配数组?

代码语言:javascript
复制
// Allocates a plain C array on the heap. The array will have
// [myArray count] items, each sized to fit a CGPoint.
CGPoint *points = calloc([myArray count], sizeof(CGPoint));
// Make sure the allocation succeded, you might want to insert
// some more graceful error handling here.
NSParameterAssert(points != NULL);

// Loop over myArray, doing whatever you want
[myArray forEachElementWithBlock:^(int idx) {
    points[idx] = …;
}];

// Free the memory taken by the C array. Of course you might
// want to do something else with the array, otherwise this
// excercise does not make much sense :)
free(points), points = NULL;
票数 14
EN

Stack Overflow用户

发布于 2011-06-22 18:19:55

另一个对我有效的简单答案是:

代码语言:javascript
复制
CGPoint points[10], *pointsPtr;
pointsPtr = points;
[myArray forEachElementWithBlock:^(int idx) {
    pointsPtr[idx] = CGPointMake(10, 20);
}];
票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5455592

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档