2

I am working on a linked list library and here is a function I wrote:

/**
 * go through a linked list and perform function func for every node of the
 * linked list
 *
 * func is a function pointer to the function you would to apply on the node.
 * it should return 0 if it is successful and non-zero value otherwise.
 */
void traverse_list(linkedlist * ll, int (* func)(void * args)){
    node * temp;

    temp = ll->head;
    while( temp != NULL ){
        if((* func)(temp->val))
            fprintf(stderr,"Error processing value!\n");
        temp = temp->next;
    }
}

My question is simple, I tried something like travers_list(testlinkedlist,printf) but it just cannot work(printf not printing anything out), what I am doing wrong? Can I do it at all, if I can, how?

Bob Fang
  • 6,963
  • 10
  • 39
  • 72

3 Answers3

2

Here's a code snippet to help you out:

#include <stdio.h>

typedef int (*func)(const char* format, ...);

int main()
{
    func a = printf;
    a("Hello World\n");
    return 0;
}

Now, if you want to create your own function that takes a variable number of arguments in C, this page from the GNU manual is a good resource to use that explains how variadic functions work.

Jason
  • 31,834
  • 7
  • 59
  • 78
1

Create your own function type that takes your list element as a parameter. There is no point in creating traversal procedure taking function as argument if the only function that matches is printf. (printf has quite unique signature)

Agent_L
  • 4,960
  • 28
  • 30
0

You should cast printf to your function's argument type:

traverse_list(my_list, (int (*) (void*))&printf);

Remember to cast it back before using it, or this is going to end up in undefined behavior.

(I'm assuming you do not want to change the parameters of your function here.)

EDIT:

If what you're really asking is what parameters should your function take, then it should be a pointer to function that corresponds to the synopsis of printf, which you can find in man 3 printf:

int printf(const char *format, ...);
cmc
  • 2,061
  • 1
  • 19
  • 18