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 ?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With