简体   繁体   English

如何在C中使用函数指针?

[英]How to use function pointer in C?

I am writing pthread program which contain functions as given below and I want to call another function in between one function. 我正在编写包含以下功能的pthread程序,并且我想在一个功能之间调用另一个功能。

void *fun1(void *arg1)
{
fun2(NULL);
}
void *fun2(void *arg)
{
fun1(NULL);
}

When I am calling another function as shown above I am getting error as shown below 当我如上所述调用另一个函数时,出现如下所示的错误

error: conflicting types for 'fun2' 错误:“ fun2”的类型冲突

note: previous implicit declaration of 'fun2' was here 注意:之前的“ fun2”隐式声明在此处

How can I call fun2 in between fun1 我如何在fun1之间调用fun2

Declare : 宣布 :

void *fun2(void *);

before fun1 fun1前1

The compiler assumes the default return type as int so you need to tell it the actual prototype before use 编译器将默认返回类型假定为int因此您需要在使用前告诉它实际的原型

During compilation you have not given a prototype for fun2 like: 在编译期间,您没有给出fun2的原型,例如:

void * fun2(void *);

Since there is no forward declaration hence the compiler implicitly assumes it will return an int . 由于没有前向声明,因此编译器隐式假定其将返回int (I mean this is how my compiler behaves) So it will have conflicting types. (我的意思是,这就是我的编译器的行为方式)因此它将具有冲突的类型。

The best practice is: 最佳做法是:

void * fun1(void *);
void * fun2(void *);

void * fun1(void *arg1)
{
    fun2(NULL);
    //return missing
}
void * fun2(void *arg)
{
    fun1(NULL);
    //return missing
}
/* forward declaration */
void *fun2(void *arg);

void *fun1(void *arg1)
{
  fun2(NULL);
}
void *fun2(void *arg)
{
  fun1(NULL);
}

Note that, as written, you have an infinite recursion. 请注意,按照书面规定,您具有无限递归。 These two functions will just call each other until the program runs out of stack and crashes. 这两个函数只会互相调用,直到程序耗尽堆栈并崩溃为止。

You must declare your function before calling it.Keep habit of declaring functions in header file or top of your .c file . 必须先声明函数,然后再习惯在头文件或.c文件顶部声明函数。 You should 你应该

void *fun2(void *args);

Lets go wild and assume that you have you have used forward declarations. 让我们疯狂地假设您已经使用了前向声明。

fun1 (there is a misnomer) calls fun2 then that calls fun1 that calls fun2 ad infinitum - until the blessed machine runs of of stack (patience?) and gives up. fun1 (有用词不当)调用fun2那么呼叫fun1的呼叫fun2循环往复-直到堆栈的祝福机器运行和放弃(耐心?)。

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

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