TimD
TimD

Reputation: 1381

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.

Upvotes: 0

Views: 230

Answers (5)

user3443267
user3443267

Reputation: 1

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

Upvotes: 0

LearningC
LearningC

Reputation: 3162

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][]

Upvotes: 0

Aean
Aean

Reputation: 779

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

Upvotes: 3

ciphermagi
ciphermagi

Reputation: 748

I think you want this:

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

Upvotes: 0

Ankit Kumar
Ankit Kumar

Reputation: 1463

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.

Upvotes: 0

Related Questions