gpt4 book ai didi

c - 函数指针 - 将参数传递给函数指针

转载 作者:行者123 更新时间:2023-12-04 09:33:11 25 4
gpt4 key购买 nike

我对使用函数指针的代码有问题,看一看:

#include <stdio.h>
#include <stdlib.h>

typedef void (*VFUNCV)(void);

void fun1(int a, double b) { printf("%d %f fun1\n", a, b); }
void fun2(int a, double b) { printf("%d %f fun2\n", a, b); }

void call(int which, VFUNCV* fun, int a, double b)
{
fun[which](a, b);
}

int main()
{
VFUNCV fun[2] = {fun1, fun2};
call(0, fun, 3, 4.5);
return 0;
}

它会产生错误:

/home/ivy/Desktop/CTests//funargs.c||In function ‘call’:|
/home/ivy/Desktop/CTests//funargs.c|11|error: too many arguments to function ‘*(fun + (unsigned int)((unsigned int)which * 4u))’|
/home/ivy/Desktop/CTests//funargs.c||In function ‘main’:|
/home/ivy/Desktop/CTests//funargs.c|16|warning: initialization from incompatible pointer type [enabled by default]|
/home/ivy/Desktop/CTests//funargs.c|16|warning: (near initialization for ‘fun[0]’) [enabled by default]|
/home/ivy/Desktop/CTests//funargs.c|16|warning: initialization from incompatible pointer type [enabled by default]|
/home/ivy/Desktop/CTests//funargs.c|16|warning: (near initialization for ‘fun[1]’) [enabled by default]|
||=== Build finished: 1 errors, 4 warnings ===|

我使用了 Code::Blocks 来编译它。

很简单,当我没有任何论据但有一些论据时,我感到困惑:

#include <stdio.h>
#include <stdlib.h>

typedef void (*VFUNCV)(void);

void fun1() { printf("fun1\n"); }
void fun2() { printf("fun2\n"); }

void call(int which, VFUNCV* fun)
{
fun[which]();
}

int main()
{
VFUNCV fun[2] = {fun1, fun2};
call(1, fun);
return 0;
}

最佳答案

您的函数指针不适合您的函数声明。尝试将其定义为

typedef void (*VFUNCV)(int, double);

关于c - 函数指针 - 将参数传递给函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18102247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com