[英]what happens here: typedef int (*ptr) (void) in .h file C
I have a piece of C code and don't understand what happens here:我有一段 C 代码,但不明白这里发生了什么:
typedef int (*ptr) (void *ptr2, const char *name);
What I do understand is the typedef int (*ptr) part, but what happens in the second()?我所理解的是 typedef int (*ptr) 部分,但是在 second() 中会发生什么? I've seen some questions where it was the other way around:
typedef void (*ptr) (int)
, is this similar or different (and how)?我已经看到了一些相反的问题:
typedef void (*ptr) (int)
,这是相似还是不同(以及如何)? I'm not the best at C, so I thought maybe *ptr now points to a function where *ptr2 and *name are declared or *ptr now points to *ptr2 and *name?我不是最擅长 C,所以我想也许 *ptr 现在指向一个函数,其中声明了 *ptr2 和 *name 或者 *ptr 现在指向 *ptr2 和 *name?
It would be great if someone could explain this to me.如果有人可以向我解释这一点,那就太好了。 Thanks in advance!
提前致谢!
If you have for example a function declaration like例如,如果您有一个函数声明,例如
int f( void *ptr2, const char *name );
(as it is seen the function type is int( void *, const char * )
) then a pointer to the function will look like (可以看出函数类型是
int( void *, const char * )
)然后指向函数的指针看起来像
int ( *pf )( void *, const char * ) = f;
and the type of the pointer pf
is int ( * )( void *, const char * )
.并且指针
pf
的类型是int ( * )( void *, const char * )
。 That is the pointer pf
now contains the address of the function f
.也就是说,指针
pf
现在包含函数f
的地址。
To introduce an alias for this function pointer type you can write要为此函数指针类型引入别名,您可以编写
typedef int (*ptr) (void *ptr2, const char *name);
In this case the above declaration of the pointer pf
will look like在这种情况下,指针
pf
的上述声明将如下所示
ptr pf = f;
that is the declaration of the pointer is simplified.也就是简化了指针的声明。
Pay attention to that the function name used as an initializer of the pointer is implicitly converted to a pointer to the function.请注意,用作指针初始值设定项的函数名被隐式转换为指向函数的指针。 That is you could write
那就是你可以写
ptr pf = &f;
but due to the implicit conversion it is enough to write但由于隐式转换,写就足够了
ptr pf = f;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.