Ilya Suzdalnitski
Ilya Suzdalnitski

Reputation: 53550

Objective C: Size of an array changes when passing to another method

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.

Upvotes: 0

Views: 976

Answers (3)

iamamac
iamamac

Reputation: 10106

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.

Upvotes: 1

avpx
avpx

Reputation: 1922

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.

Upvotes: 5

Idan K
Idan K

Reputation: 20881

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.

Upvotes: 6

Related Questions