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?

4

3 に答える 3

2

ここにあなたを助けるためのコードスニペットがあります:

#include <stdio.h>

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

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

ここで、C で可変数の引数をとる独自の関数を作成したい場合は、GNU マニュアルのこのページを使用すると、可変個引数関数がどのように機能するかが説明されています。

于 2013-01-07T20:35:06.513 に答える
1

リスト要素をパラメーターとして受け取る独自の関数型を作成します。一致する唯一の関数がprintf. (printf は非常にユニークな署名を持っています)

于 2013-01-07T20:42:04.277 に答える
0

printf を関数の引数の型にキャストする必要があります。

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

使用する前にキャストバックすることを忘れないでください。そうしないと、未定義の動作になってしまいます。

(ここで関数のパラメーターを変更したくないと仮定しています。)

編集:

あなたが本当に求めているのが、関数がとるべきパラメータである場合、それは printf の概要に対応する関数へのポインタである必要がありますman 3 printf

int printf(const char *format, ...);
于 2013-01-07T20:36:37.093 に答える