简体   繁体   中英

Returning a 2D array from c function

I'm a python programmer writing some c (wrapped in ctypes) to speed up some tight loops. I'm having trouble with a function that takes a two dimensional array (*double)[2] , does some things to it and returns it. Function looks something like the following:

double *process(int n, double (*results)[2], ...) {
    // Do some things to results
    return results;
}

Here, n is the number of elements in the first level of results. This doesn't compile, apparently I'm returning from an incompatible pointer type. Making it return *results allows it to compile and run (all the contained logic is fine), but segfaults at the return. Making the function a double ** and returning with any number of * s doesn't let me compile.

Clearly I'm being an idiot here, which isn't surprising at all as I don't really understand c pointers. What do I need to do to make this work? I've got another function that returns a double * working fine, so it's clearly something to do with the 2D array.

If you just want to get new results you even don't need to return anything. The array is passed by address, not values.

void process(int n, double results[][2], ...) {
    // Do some things to results,
    results[n][0] = 1.0l;
    // And no need to return.
}
int main(){
    double array[2][2] = { .0 };
    printf( "Before process: %lf", array[1][0] );
    process( 1, array );
    printf( "After process: %lf", array[1][0] );
}

It should output:

Before process: 0.0000000000
After process: 1.0000000000

to return 2D array you need to use

double **

To take a 2D array as parameter in function process() you can use

double *results[2]

or

double results[2][]

Your function's return value expects only a 1D array as return value. to make it work with 2D arrays, make it double ** .

when you're returning, return only results . don't put any * in front of it.

I think you want this:

double ** process(int n, double ** results)
{
    /* Do stuffz */
    return results;
}

You probably want to return a pointer to a two dimension array. In this case you would have to use:

double (*process (int n, double results[][2], ...))[2] {
  return results;
}

This basically means "return a pointer to two 2 elements of double"

Or, to make it somehow more readable:

typedef double arrayType[2];

arrayType * process(int n, double results[][2]) {
    return results;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM