Reputation: 7
A function returns a void double pointer containing a pointer to a float array, how can i access the output data?
void **pointer;
// function(void **ptr)
function(pointer);
This pointer points has to point to a float type pointer.
float *coords;
coords = (float*)malloc(3*500*sizeof(float)); //I know the amount of memory to be allocated
How can I read the data from this void double pointer? I'm pretty confused.
Upvotes: 1
Views: 5069
Reputation: 76
Your function prototype is not with respect to what you want to achieve. If you want your function to allocate memory and send its reference back to the main then your function will look like this (considering you want to pass double pointer) :
void function(void ***ptr)
{
float *coords;
coords = (float*)malloc(3*500*sizeof(float));
*ptr = (void **) &coords;
//do something
return;
}
main()
{
void **pointer;
function(&pointer);
/* Accessing first member of array allocated in function */
printf("%f", (*((float **)pointer))[0]);
}
If this is the objective, there is simpler way :
void function(void **p)
{
float *coords;
coords = (float*)malloc(3*500*sizeof(float));
*p = coords;
return;
}
main()
{
void *pointer;
function(&pointer);
printf("%f", ((float*)pointer)[0]);
}
Hope this helps.
Upvotes: 2
Reputation: 52622
Please check your code. What you are posting is nonsense - you have an uninitialised variable and pass it to a function. That's undefined behaviour and can crash or worse before the function even starts executing.
I think you are confused by what you call a "double pointer". There is no such thing as a "double pointer". A pointer points to something, it doesn't double-point. A pointer might point to an int (an int*), or to a struct T (struct T*) or to a float* (a float**). In the float** there are two *'s, but that doesn't make it a "double pointer". It is an ordinary pointer that happens to be pointing to something that is itself a pointer.
Pointers as function parameters are most often used so that the function can return more than one value. Say a function get_width_and_height returning to ints:
void get_width_and_height (int* width, int* height) {
*width = 10;
*height = 20;
}
int x, y;
get_width_and_height (&x, &y);
Now with that example in mind, how would you write a function that returns two int and one float* ?
Upvotes: 0
Reputation: 60027
I am going to have to make a few assumptions here as the question is unclear
I am going to assume that you call the function thus:
void **pointer;
function(pointer);
Then want to access the output, so do
flow *coord = (float *) *pointer;
Then you are home free
Upvotes: -1