gpt4 book ai didi

c - 为什么 func 看起来和 C 中的 &func 一样?

转载 作者:行者123 更新时间:2023-12-04 00:53:18 25 4
gpt4 key购买 nike

<分区>

根据GNU C manual , 可以像这样使用函数指针调用函数:

func (j);  /* (*func) (j); would be equivalent. */

所以我的推理是:func 本身是指向 func(int) 函数的指针。当您调用 func(j) 时,您正在隐式访问指针 func 的值(您正在移动到 func 所在的内存位置),就像你有一个指向整数的指针一样,例如,你可以使用 * 访问存储在内存该位置的值。这与您可以使用 (*func)(j) 调用相同函数这一事实是一致的。

事实上,在cprogramming.com ,他们说你可以有一个指向函数指针的指针。因此,我猜测它们的工作方式与任何其他类型的指针一样。

但如果是这样,为什么这段代码有效?

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

void a(int n) {
printf("%d\n", num);
}

int main() {
int x = 5;
void (*func)(int); // Declare a pointer to a function
func = &a; // Pointer to a pointer to a function
(*func)(x); // Calls the function (why?)
func = a; // Pointer to a function
(*func)(x); // Calls the function (makes sense)
}

此外,如果你调用:

printf("%s\n", (&a == a) ? "True" : "False");

它打印True!

例如,我确定 &foo&&foo 不同,所以 为什么 func&func 一样吗?

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