如何解决无法理解函数中 c 中的指针
我正在网站上阅读此代码。我对编程还很陌生,所以请详细解释一下。
#include <stdio.h>
// A normal function with an int parameter
// and void return type
void fun(int a)
{
printf("Value of a is %d\n",a);
}
int main()
{
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;
/* The above line is equivalent of following two
void (*fun_ptr)(int);
fun_ptr = &fun;
*/
// Invoking fun() using fun_ptr
(*fun_ptr)(10);
return 0;
}
疑问-
我无法理解这种类型的声明和赋值void (*fun_ptr)(int) = &fun;
我的意思是,如果我们声明一个数据类型,那么我们会像 int a;
一样将其分配为 a=10;
,但在这里我们通过编写 (*fun_ptr)(10);
来分配它。请帮忙。
解决方法
代替这条记录
(*fun_ptr)(10);
你可以写
fun_ptr(10);
也就是说它是函数指针fun
所指向的函数fun_ptr
的函数调用,因为函数地址在其声明中对该指针进行了初始化
void (*fun_ptr)(int) = &fun;
反过来这个声明可以写得更简单
void (*fun_ptr)(int) = fun;
因为在表达式中使用的函数指示符(在本例中为 fun
)作为初始化器被隐式转换为指向函数的指针。
您可以通过以下方式为函数类型使用 typedef 别名
typedef void Func( int );
在这种情况下,函数指针的上述声明可能看起来更简单
Func *fun_ptr = fun;
这是使用函数 fun
的函数类型的 typedef 重写的程序。
#include <stdio.h>
typedef void Func( int );
// Function declaration without its definition using the typedef
// This declaration is redundant and used only to demonstrate
// how a function can be declared using a typedef name
Func fun;
// Function definition. In this case you may not use the typedef name
void fun( int a )
{
printf("Value of a is %d\n",a);
}
int main(void)
{
// Declaration of a pointer to function
Func *fun_ptr = fun;
// Call of a function using a pointer to it
fun_ptr( 10 );
return 0;
}
,
让我们稍微改写一下,使用类型别名和一些注释:
// Define a type-alias names fun_pointer_type
// This type-alias is defined as a pointer (with the asterisk *) to a function,// the function takes one int argument and returns no value (void)
typedef void (*fun_pointer_type)(int);
// Use the type-alias to define a variable,and initialize the variable
// This defines the variable fun_ptr being the type fun_pointer_type
// I.e. fun_ptr is a pointer to a function
// Initialize it to make it point to the function fun
fun_pointer_type fun_ptr = &fun;
// Now *call* the function using the function pointer
// First dereference the pointer,to get the function it points to
// Then call the function,passing the single argument 10
(*fun_ptr)(10);
希望它能让事情稍微更清楚发生了什么。
,以下是两个声明的含义。
void (*fun_ptr)(int) = &fun;
这称为在同一行中声明和初始化 fun_ptr
,这与执行 int a = 10;
(*fun_ptr)(10);
不是赋值语句,它是通过函数指针 fun
调用函数 fun_ptr
。
您还可以使用 typedef
创建一个由函数指针定义的新用户,并按照上述答案使用。
如果您不熟悉编程,这是一个高级主题,fun_ptr
是指向函数的指针。
声明:
void (*fun_ptr)(int) = fun;
表示 fun_ptr
是指向函数的指针,该函数采用 int
参数并返回 void
,如果使用指向函数 fun
的指针进行初始化。 (您不需要 &
)
行:
(*fun_ptr)(10);
不分配任何东西,它调用fun_ptr
指向的函数,但很复杂
fun_ptr(10);
当 fun_ptr
指向 fun
这相当于 `fun(10)。
使用函数指针有其用途,例如在排序函数中,比较函数作为函数指针传入,因此调用之间的排序可能不同。 达到了同样的效果,而且对眼睛来说更容易。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。