【问题标题】:Objective C: Size of an array changes when passing to another method目标 C:数组的大小在传递给另一个方法时发生变化
【发布时间】:2010-01-02 19:41:08
【问题描述】:

我有一个小问题。我有一个数组,当从 Objective-C 函数传递给 C 函数时,它的大小会发生变化。

void test(game_touch *tempTouches)
{
    printf("sizeof(array): %d", sizeof(tempTouches) );
}

-(void)touchesEnded: (NSSet *)touches withEvent: (UIEvent *)event
{
    game_touch tempTouches[ [touches count] ];
    int i = 0;

    for (UITouch *touch in touches)
    {
        tempTouches[i].tapCount = [touch tapCount];

        tempTouches[i].touchLocation[0] = (GLfloat)[touch locationInView: self].x;
        tempTouches[i].touchLocation[1] = (GLfloat)[touch locationInView: self].y;

        i++;
    }

    printf("sizeof(array): %d", sizeof(tempTouches) );

    test(tempTouches);
}

控制台日志是:

[touchesEnded] sizeof(array): 12
[test] sizeof(array): 4

为什么两种方法的大小不同?

在 [test] 方法中,返回大小始终为 4,与数组的原始大小无关。

谢谢。

【问题讨论】:

标签: iphone objective-c cocoa-touch


【解决方案1】:

在 C 数组中,当它们作为参数传递时,它们会衰减为指针。 sizeof 运算符无法知道传递给 void test(game_touch *tempTouches) 的数组的大小,从它的角度来看,它只是一个大小为 4 的指针。

当使用这种语法int arr[20] 声明数组时,大小在编译时是已知的,因此sizeof 可以返回它的真实大小。

【讨论】:

    【解决方案2】:

    尽管 C 中的数组和指针有很多相似之处,但如果您不熟悉它们的工作方式,这可能会让人感到困惑。本声明:

    game_touch tempTouches[ [touches count] ];
    

    定义一个数组,因此 sizeof(tempTouches) 返回该数组的大小。但是,当数组作为参数传递给函数时,它们会作为指向它们占用的内存空间的指针传递。所以:

    sizeof(tempTouches)
    

    在你的函数中返回指针的大小,而不是数组的大小。

    【讨论】:

      【解决方案3】:

      test 中,tempTouches 是指向数组第一个元素的指针。

      您还应该将数组元素的数量传递给函数。

      【讨论】:

        猜你喜欢
        • 2012-12-12
        • 2013-09-20
        • 1970-01-01
        • 2017-04-30
        • 1970-01-01
        • 2017-11-15
        • 2016-12-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多