gpt4 book ai didi

c++ - C函数指针

转载 作者:太空宇宙 更新时间:2023-11-04 00:54:59 24 4
gpt4 key购买 nike

static void increment(long long *n){
(*n)++;
}

struct test{
void (*work_fn)(long long *);
};

struct test t1;

t1.work_fn = increment;

我现在如何实际调用该函数? t1.work_fn(&n) ?

最佳答案

How do I actually call the function now? t1.work_fn(&n) ?

那会很好用的。

不需要明确取消引用函数指针。这是因为即使在正常调用函数时(使用函数的实际名称),您实际上也是通过指向函数的指针来调用它。 C99 6.5.22“函数调用”说(强调我的):

The expression that denotes the called function (footnote 77) shall have type pointer to function returning void or returning an object type other than an array type

脚注 77:

Most often, this is the result of converting an identifier that is a function designator.

请注意,您仍然可以取消引用函数指针(或普通函数名称 - 虽然我认为这样做会引起很多混淆)以调用函数,因为 C99 6.5.3.2/4“地址和间接运算符”说:

The unary * operator denotes indirection. If the operand points to a function, the result is a function designator

所以所有这些最终都会做同样的事情(尽管编译器可能无法优化通过 t1.work_fn 的调用):

t1.work_fn(&n);
(*t1.work_fn)(&n);

increment(&n);
(*increment)(&n);

关于c++ - C函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5834520/

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