Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple pointers from function

Tags:

c

pointers

I'm trying to return 4 pointers which are stored in another pointer from a function in C, but I get segmentation fault. Do anyone know how to do this?

That's the way I tried to do this:

//declaration of 5 pointers (int * ptr0, float * ptr1, ..., int * ptr4)

int * function()
{
    int * ptr;
    ptr = malloc(sizeof(int)*4);

    float * ptr1;
    ptr1 = malloc(sizeof(float)*4);

    float * ptr2;
    ptr2 = malloc(sizeof(float)*4);

    float * ptr3;
    ptr3 = malloc(sizeof(float)*4);

    int * ptr4;
    ptr4 = malloc(sizeof(int)*4);

    retunr ptr;
}

ptr0 = function();
ptr1 = ptr0[0];
ptr2 = ptr0[1];
//and so on...

Ok, I changed my program but now I can not write in the pointers anymore. I know this is a realy 'stupid' question but I realy dont know. Can someone help ?

like image 717
noName Avatar asked May 28 '26 18:05

noName


1 Answers

You can only return a singe value from a function. A simple solution is to return a struct that contains the desired pointers.

struct pointers {
    float* ptr1;
    float* ptr2;
    float* ptr3;
    // or perhaps an array instead:
    // float* f_ptrs[3];
    int*   ptr4;
}

struct pointers function() {
    struct pointers p;
    // initialize the members here
    return p;
}
like image 195
eerorika Avatar answered May 30 '26 09:05

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!