c - 警告 : Assignment from Incompatible Pointer Type [enabled by default] while assigning Function Address to Function Pointer

标签 c function pointers function-pointers

我正在尝试使用函数指针实现一个简单的交换函数,但是当我将函数的地址分配给函数指针时:

`pointersTofunctionB.c:14:6:warning: 从不兼容的指针类型赋值 [默认启用]。

这是我的代码:

#include <stdio.h>
void intSwap(int *a,int *b);
void charSwap(char *a,char *b);
void (*swap)(void*,void*);
int main(int argc, char const *argv[])
{
    int a=20,b=15;
    char c='j',d='H';
    swap=&intSwap;// warning here
    swap(&a,&b);
    printf("%d %d\n",a,b);
    swap=&charSwap;// warning here also
    swap(&c,&d);
    printf("%c %c\n",c,d ); 
    return 0;
}


void intSwap(int *a,int *b)
{
    *a=*a+*b;
    *b=*a-*b;
    *a=*a-*b;
}
void charSwap(char *a,char *b)
{
    char temp;
    temp=*a;
    *a=*b;
    *b=temp;
}

我该如何解决这个警告?

最佳答案

出现警告是由于以下 C 标准引用

6.3.2.3 指针

8 A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined.

两个函数是兼容的,它们的参数应该有兼容的类型

6.7.6.3 函数声明符(包括原型(prototype))

15 For two function types to be compatible, both shall specify compatible return types.146) Moreover, the parameter type lists, if both are present, shall agree in the number of parameters and in use of the ellipsis terminator; corresponding parameters shall have compatible types.

在您的函数中,参数被声明为指针。为了使它们(指针)兼容,它们应该是指向兼容类型的指针

6.7.6.1 指针声明符

2 对于要兼容的两个指针类型,两者都应具有相同的限定,并且都应是指向兼容类型的指针。

但是,一方面类型为 int 或 char,另一方面类型为 void 是不兼容的类型。

您可以通过以下方式定义您的函数

void intSwap( void *a, void *b )
{
    int *x = a;
    int *y = b;

    *x = *x + *y;
    *y = *x - *y;
    *x = *x - *y;
}

void charSwap( void *a, void *b )
{
    char *c1 = a;
    char *c2 = b;
    char temp = *c1;

    *c1 = *c2;
    *c2 = temp;
}

关于c - 警告 : Assignment from Incompatible Pointer Type [enabled by default] while assigning Function Address to Function Pointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27632217/

相关文章:

Javascript 函数调用具有可选属性

c++ - 指向对象的指针数组不会填满其分配的容量

c - malloc中sizeof的使用

c - 如何使用递归[C]对数字进行求和?

c - SPOJ COINS DP 和递归方法

c11:使用 _Generic 引发 SIGSEGV

c - 如何在大指针中打印字节子集?

javascript - 函数只返回事件

php - 如何处理 PHP 中 file_get_contents() 函数的警告?

c - "Makes Pointer from Integer without a Cast"- 如何满足 GCC?