malajedala malajedala - 3 months ago 12
C Question

Interface with variable argument list function, by using function pointers

I am trying to use an interface of another program, where I have to use the following method:

void iterate_over_entries(Table* table, Func_ptr f, ... )


so the function is designed to call on each table entry the function f() which is user-defined.

The function pointer is defined as:

typedef size_t (*Func_ptr) (char* example, va_list args);


So that means that I have to write a function which is of type Func_ptr in order to manipulate the entries of the table?

So lets say for example I want to whatever - set all strings which have a length below a given one to be "a". Is it then, that I have to put the length into this va_list?

size_t my_method(char* example, va_list args) {

int length = va_arg(args, int);

if (strlen(example) < length) strncpy(example, "a\0", 2);

return 1;
}


So If I did everything so far correct, I only need to call the function, but I have no idea how to do that.. Lets say I want that the command line input sets me the length I allow...

int main(int argc, char** argv){

Table* table; //this is set somehow..

int length = atoi(argv[1]);

size_t (*method)(char* example, va_list list);
method = &my_method;

}


So how do I now tell the program to call iterate_over_entries with with my_method, where the length to my input... :S

Answer

Just call it:

int main(int argc, char** argv){ 

    Table* table; //this is set somehow.. 

    int length = atoi(argv[1]);

    Func_ptr method;
    method = &my_method;
    iterate_over_entries(table, method, length);

 }

There's no need to assign my_method to another variable, you can just pass it directly.

    iterate_over_entries(table, my_method, length);
Comments