2

If I want to define a pointer variable p to point to the function foo() defined as below, what should be the exact type of p?

int *foo(void *arg)
{
    ...
}

5 Answers 5

4

It should be

typedef int *(*funtion_foo_type)(void *);
Sign up to request clarification or add additional context in comments.

4 Comments

Actually, I would suggest that defining a typedef for the function signature, that is like the function but with typedef before, e.g. typedef int*foo_type(void*); then using a pointer to that type, i.e. foo_type* funptr; is even more readable
However, this is not a type. This is a type definition operator.
@KyryloPolezhaiev: typedef is not an operator. Syntactically it is a storage-class specifier. A typedefed name is an alias for the actual type.
Sorry, I meant statement. I didn't mean typedef, I meant whole string. Tried to avoid confusion, made more confusion (:
4

You need to have the pointer as the pointer to a function, returning an int *, accepting a void* argument. You can make it like

int * (*p) (void *);

and then, you can use

p = foo;

Comments

3

Bearing in mind the comment of Kyrylo Polezhaiev, the type of p is

int*(*)(void*)

To declare p, you need to insert the name at the correct point in the type:

int*(*p)(void*);

but it is generally more readable to use an alias:

typedef int*(func_t)(void*);
func_t* p;

Comments

1

To make it more easy you could for the function declaration

int *foo(void *arg);

define an alias named as for example Tfoo that looks the same way as the function declaration itself

typedef int *Tfoo(void *);

After that to declare a function pointer to the function is very easy. Just write

Tfoo *foo_ptr = foo;

Otherwise you could write

typedef int * (* TFoo_ptr )(void *);

Tfoo_ptr foo_ptr = foo;

Or you could write a declaration of the function pointer directly without using the typedef/

int * (* foo_ptr )(void *) = foo;

Comments

1

Are you talking about pointer to function?

First define a pointer to function that takes void argumenta and return int

typedef   int (*Ptrtofun)(void); 

Now safely can point this to your function.

Ptrtofun p;
p = &foo(void);

Now you have a ptr p to function and can easily use it ..

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.