目标C:传递给另一个方法时,数组的大小会发生变化

Ily*_*ski 0 iphone cocoa-touch objective-c

我有一个小问题.当从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);
}
Run Code Online (Sandbox Code Playgroud)

控制台日志是:

[touchesEnded] sizeof(array): 12
[test] sizeof(array): 4
Run Code Online (Sandbox Code Playgroud)

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

在[test]方法中,返回大小始终为4,而不依赖于数组的原始大小.

谢谢.

Ida*_*n K 6

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

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


avp*_*vpx 5

尽管C中的数组和指针有许多相似之处,但这是其中一种情况,如果您不熟悉它们的工作方式,则可能会造成混淆.这个说法:

game_touch tempTouches[ [touches count] ];
Run Code Online (Sandbox Code Playgroud)

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

sizeof(tempTouches)
Run Code Online (Sandbox Code Playgroud)

在您的函数中返回指针的大小,这不是数组的大小.