views:

181

answers:

3

Hi, I've got a small problem. I've got an array and its size changes when passing to a c-function from an objective-c function.

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);
}

The console log is:

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

Why is the size different in 2 of the methods?

In the [test] method the returning size is always 4, not depending on the original size of an array.

Thanks.

+6  A: 

In C arrays decay into pointers when they are passed as parameters. The sizeof operator has no way of knowing the size of the array passed to void test(game_touch *tempTouches), from it's perspective it's merely a pointer whose size is 4.

When declaring arrays using this syntax int arr[20], the size is known at compile-time therefore sizeof can return it's true size.

Idan K
+4  A: 

Although arrays and pointers in C have many similarities, this is one of those cases where, if you are unfamiliar with how they work, it can be confusing. This statement:

game_touch tempTouches[ [touches count] ];

Defines an array, so sizeof(tempTouches) returns the size of that array. When arrays are passed as arguments to functions, however, they are passed as pointers to the space in memory they occupy. So:

sizeof(tempTouches)

in your function returns the size of the pointer, which is not the size of the array.

avpx
+1  A: 

In test, tempTouches is a pointer to the first element of the array.

You should also pass the number of elements of the array to the function.

Iamamac