0

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.

1
  • double (*results)[2] is meant to receive 2D array here? Commented Mar 20, 2014 at 16:06

5 Answers 5

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

This makes some degree of sense, I think I've still got problems with ctypes here and not the c
0

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.

Comments

0

I think you want this:

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.