Ad

From Objective-c To Double Array C Code Function Argument

- 1 answer

Hi I am getting a problem when passing an argument double array from Objective-c to C Code somehow when receiving to c code my data is not an array anymore. can you point out what is wrong with my code

objective-c objective-c code

C code c code

Sorry for a newbie question, I am still new to C Code

Ad

Answer

Those are the same. On the Objective-C side it is shown as a double array and on the C side as a pointer to double, which is the same. Note how the first value in the array is the same as the first value pointed to by the pointer.

You can use e.g.

double value = * ( data + i );

to get the value pointed to at index i from the array.

Also, change the arguments of the C function as follows.

int classify_data( double * data, int size )

and pass the data in as now and also the size of the array.

EDIT

FWIW the code below hopefully clarifies this similarity.

        double data[] = { 1.0, 22222.0, 3.0 };
        double * p = data;

        // All print the same 22222
        NSLog(@"Some values %f %f %f %f", * ( data + 1 ), data[ 1 ], * ( p + 1 ), p[ 1 ] );

If you work with the pointer you can loop using pointer arithmetic which can be really nice and efficient, but that is a topic on its own. The pointer and the array can be used interchangeably as shown in the code because, in C, they are the same.

EDIT 2 A sample of how you could loop a double array extremely efficiently.

double sum ( double * data, int n )
{
    double sum = 0;

    while ( n )
    {
        // The more traditional way of doing it
        sum += * data;
        data ++;

        // Here you can even write a one-liner as below which is extremely efficient
        // This line below is a real nice example of how powerful pointer arithmetic is ...
        // sum += * ( data ++ );

        n --;
    }

    return sum;
}
Ad
source: stackoverflow.com
Ad