本文介绍了这是一个通用的函数指针和它是危险的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习和函数指针搞乱了,我发现一个方法来初始化空函数指针和扮演他们。然而,尽管我没有收到任何警告或错误,无论是与海湾合作委员会或VS的编译器,我想知道它是否是危险的或坏的做法,这样做,因为我没有看到的往往初始化函数指针的这种方式互联网。此外,我们称这种通用的函数指针?

的#include<&stdio.h中GT;
#包括LT&;&stdint.h GT;
#包括LT&;&CONIO.H GT;的#define PAUSE(_getch())uint16_t添加(常量uint16_t X,常量uint16_t Y){
    返回X + Y;
}字符CHR(uint8_t有测试){
    返回(焦炭)的测试;
}诠释主要(无效){    无效(*测试)()=(无效*)增加;    常量uint16_t X = 1,Y = 1;
    uint16_t值=((uint16_t(*)())测试)(X,Y);    测试=(无效*)CHR;    的printf(%d个\\ N,加(X,Y)); // 2
    的printf(%d个\\ N,值); // 2
    的printf(%C \\ n,((CHAR(*)())测试)(100)); //ð    暂停;
    返回0;
}


解决方案

No, if I'm not terribly mistaken, there's no such thing as a "generic function pointer" in C.

Yes, it is. It is evil.


There are a couple of things you need to know. First, unless you are running a system that conforms to POSIX,

void(*test)() = (void*)add;

is wrong. void * is a pointer-to-object type, and as such, it is not compatible with function pointers. (At least not in standard C -- as I mentioned, POSIX requires it to be compatible with function pointers too.)

The second thing is that void (*fp)() and void (*fp)(void) are different. The former declaration permits fp to take any number of parameters of any type, and the number of arguments and their types will be inferred when the compiler sees the first call to the function (pointer).

Another important aspect is that function pointers are guaranteed to be convertible across each other (AFAIK this manifests in them having the same representation and alignment requirements). This means that any function pointer can be assigned to (the address of) any function (after an appropriate cast), so long as you do not call a function through a pointer to an incompatible type. The behavior is well-defined if and only if you cast the pointer back to the original type before calling it.

So, if you want a "generic" function pointer, you can just write something like

typedef void (*fn_ptr)(void);

and then you could assign any pointer to function to an object of type fn_ptr. What you have to pay attention to is, again, the conversion to the right type when invoking the function, as in:

int add(int a, int b);

fn_ptr fp = (fn_ptr)add; // legal
fp(); // WRONG!
int x = ((int (*)(int, int))fp)(1, 2); // good

这篇关于这是一个通用的函数指针和它是危险的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 23:07