2010-01-02 21 views
0

我遇到了一个小问题。从一个objective-c函数传递给c函数时,我得到一个数组并且它的大小发生了变化。Objective 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 

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

在[test]方法中,返回大小始终为4,而不取决于数组的原始大小。

谢谢。

+0

相关: http://stackoverflow.com/questions/720077/calculating-size-of-an-array – whunmr 2010-01-02 19:47:46

回答

6

在C数组中,当它们作为参数传递时会衰减为指针。 该sizeof操作者不知道传递给void test(game_touch *tempTouches)阵列的尺寸的方式,从它的角度看,它是仅仅是一个指针,其尺寸为4

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

5

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

game_touch tempTouches[ [touches count] ]; 

定义的阵列,所以的sizeof(tempTouches)返回该数组的大小。然而,当数组作为参数传递给函数时,它们会作为指针传递给它们占用的内存中的空间。所以:

sizeof(tempTouches) 

在函数返回指针,这不是数组的大小尺寸。

1

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

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

相关问题