Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/C function pointers that return void*

I'm trying to call a function that takes an argument, void(*)(void*, int, const char*), but I cannot figure out how to pass those arguments to the function.

Example:

void ptr(int);
int function(int, int, void(*)(int));

I am trying to call the function like this:

function(20, 20, ptr(20));

Is this possible?

like image 391
bryan sammon Avatar asked Feb 04 '12 18:02

bryan sammon


People also ask

What is void * return type in C?

In computer programming, when void is used as a function return type, it indicates that the function does not return a value. When void appears in a pointer declaration, it specifies that the pointer is universal.

What does a void * return?

In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value. You may or may not use the return statement, as there is no return value.

Can C functions return void?

If a return value isn't required, declare the function to have void return type. If a return type isn't specified, the C compiler assumes a default return type of int . Many programmers use parentheses to enclose the expression argument of the return statement. However, C doesn't require the parentheses.

Which of the following function returns a void pointer?

The malloc() and calloc() function return the void pointer, so these functions can be used to allocate the memory of any data type.


1 Answers

You are doing one thing incorrectly - you are trying to invoke your 'ptr' function before invoking 'function'. What you were supposed to do is to pass just a pointer to 'ptr' and invoke 'ptr' using passed pointer from 'function' like that:

void ptr(int x)
{
    printf("from ptr [%d]\n", x);
}

int function(int a, int b , void (*func)(int) )
{
    printf( "from function a=[%d] b=[%d]\n", a, b );
    func(a); // you must invoke function here

    return 123;
}


void main()
{
    function( 10, 2, &ptr );
    // or
    function( 20, 2, ptr );
}

which gives:

from function a=[10] b=[2]
from ptr [10]
from function a=[20] b=[2]
from ptr [20]

which is what you wanted

for

function(20, 20, ptr(20));

to work - you would have to have sth like:

// 'ptr' must return sth (int for example)
// if you want its ret val to be passed as arg to 'function'
// this way you do not have to invoke 'ptr' from within 'function'
int ptr(int);
int function(int, int , int);
like image 133
Artur Avatar answered Oct 04 '22 02:10

Artur