简体   繁体   English

在C中使用typedef函数指针

[英]Using typedef function pointer in C

I am trying to use function pointer, which is somewhat like this: 我正在尝试使用函数指针,这有点像这样:

#include "stdio.h"

typedef void (*func)(int*, int*);


void func1(int *a, int*b)
{
    printf("Func1\n");
}

void func2(int *a, int*b)
{
    printf("Func2\n");
}

void func3(int *a, int*b)
{
    printf("Func3\n");
}

int main()
{
    int i;
    func f[] = {
      func1, func2, func3
    };
    printf("Hello\n");

    for(i=0; i< 3; i++)
    {
        func fn = f[i];
        *(fn)(&i, &i);
    }
    return 0;
}

I am always getting error: "void value not ignored as it ought to be" 我总是得到错误:“无效值不应该被忽略”

Do not know, how to overcome this. 不知道,该如何克服。 Can anybody please help? 有人可以帮忙吗?

您需要使用如下所示:

(*fn)(&i, &i);

It's either (*fn)(&i, &i) , or just fn(&i,&i) . 它是(*fn)(&i, &i)或仅仅是fn(&i,&i) Otherwise you're trying to dereference the result of the function call! 否则,您将尝试取消引用函数调用的结果!

(Alternatively, five-star-programmers often say (*****fn)(&i, &i) . (或者,五星级程序员经常说(*****fn)(&i, &i)

This error means you assign the return of a void function to something, which is an error. 此错误表示您将void函数的返回值分配给了某个对象,这是一个错误。

Try this:- 尝试这个:-

(*fn)(&i, &i);

尝试这个:

(*fn)(&i, &i);

Don't write *(fn)(...) - simple fn(...) is enough, no need to dereference anything. 不要写*(fn)(...) -简单的fn(...)就足够了,不需要取消引用任何东西。 What you have means something like "Dereference the return value of fn(...)", but you obviously can't do that. 您所拥有的含义类似于“取消引用fn(...)的返回值”之类的东西,但是您显然无法做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM