1

Hey so i am trying to figure out how i pass a function pointer to a function stored within a struct. The following is the typedef

struct menu_item
{
    char name[ITEM_NAME_LEN+1];
    BOOLEAN (*func)(struct vm*);

};

The function i am trying to pass has the following prototype.

void print_list(struct vm_node  *root);

with the defintion of the file being:

void print_list(struct vm_node  *root) {
    while (root) {
        printf("%s",root->data->id);
        root = root->next;
    }
    printf("\n");
}

2 Answers 2

1
struct menu_item item;
item.func = &print_list;

As simple as that. However BOOLEAN (*func)(struct vm*); needs to be changed to void (*func)(struct vm_node *); to match the destination function.

Sign up to request clarification or add additional context in comments.

9 Comments

The address of operator isn't needed at &print_list. print_list decays to a function pointer similar to how an array decays to a pointer.
@krypton the func will have to accept various other functions which will return other types.
@tangrs: with ampersand is a more correct way of understanding.
@JoshuaTheeuf: if you want it to accept various types function prototype, simply declare as void (*func)(), but then you would need to do type enforcing to prevent compiler warnings.
@JoshuaTheeuf the func will have to accept various other functions which will return other types - this is generally a bad idea. But if you really must do this, you can create a union of possible return types, and have all your functions return that union.
|
0

functions are sort of like arrays so you can just do

menu_item.func = print_list;

just like you would do with an array

int arr[20];
int *ptr;
ptr = array /*

2 Comments

Do you know what the above line does?
OP wants a function pointer as far as I can see, not the result of a function call.

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.