![](/img/trans.png)
[英]Why typedef to a function is required, while casting void* to function pointer?
[英]is * mandatory while doing typedef of a function pointer?
当我写了一段“无意识的”代码时,我开始回答这个问题,并成功编译并得到了理想的行为。 后来我注意到了变化的奇怪之处,并意识到我使用了完成相反的顺序来执行函数指针的typedef。 如果“意外”的错误实际上在语法上是正确的,那么我很困惑。
惯例:
typedef void* (*_malloc_fail_handler_ptr)(int) __attribute__ ((unused));
_malloc_fail_handler_ptr _malloc_fail_handler = NULL;
我的“非预期”代码:
typedef void* (_malloc_fail_handler_ptr)(int) __attribute__ ((unused));
_malloc_fail_handler_ptr* _malloc_fail_handler = NULL;
这是正确的语法。 对于_malloc_fail_handler_ptr
情况, _malloc_fail_handler_ptr
的类型是函数,而不是函数指针。 然后_malloc_fail_handler_ptr*
的类型是指向函数的指针。 因此,对于第1和第2种情况,变量_malloc_fail_handler
的类型是相同的。
第二个问题唯一的问题是命名:
typedef void* (*_malloc_fail_handler_ptr)(int) __attribute__ ((unused));
在那里, _malloc_fail_handler_ptr
是一个指向函数的指针,它接受一个int
并返回void*
。
typedef void* (_malloc_fail_handler_ptr)(int) __attribute__ ((unused));
这里, _malloc_fail_handler_ptr
是一个接受int
并返回void*
的函数。 它是一个函数类型,而不是指针类型。 所以后缀_ptr
是误导性的。 但是像任何(在C ++中,非引用)类型一样,你总是可以编写T*
来获取指向T
的指针,所以这是有效的。
简化一切以避免笨拙的函数语法,您的问题归结为:
typedef int* ptr;
ptr x = NULL;
与:
typedef int ptr;
ptr* x = NULL;
两者在语法上都很好,但第二个是非常误导性地命名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.