c - 对于函数指针 "fptr",为什么 "fptr"和*fptr的值相同?*fptr到底是什么意思?我只知道(*fptr)()或fptr()

标签 c function-pointers

<分区>

就此行为而言,为什么 函数指针 表现得像 数组指针?我的意思是,让我们从数组 list[ ] 我们将在其中考虑 &listlist

 char name[5]= "Eric",(*aptr)[5]=&name;
 printf("%p,%p",*aptr,name); //BOTH ARE NUMERICALLY SAME

我们也可以将数组元素称为 (*aptr)[1](*aptr)[2] 等。我明白这里发生了什么.

但为什么同样适用于函数?毕竟这样的“函数”不是与数组相似的元素的连续内存块。考虑一下。

假设fptr是我程序中的函数指针。为什么fptr*fptr在打印时给出相同的值?什么是*fptr 甚至是什么意思?我只知道我们可以使用它的指针作为 (*fptr)()fptr() 来调用函数,但是 *fptr 又是什么呢?

#include<stdio.h>

void foo(){};

int main(void)
{
void (*fptr)()=foo;
printf("%p,%p",fptr,*fptr);

}

结果- 00401318 00401318

最佳答案

指针是指向一个内存位置。一个函数在内存中并且有一个起始地址。您可以很好地取消引用函数名称(这是一个指针)以获取该地址的函数。

来自 Stephen Prata“Cpp Primer Plus


History Versus Logic Holy syntax!


How can pf and (*pf) be equivalent? One school of thought maintains that because pf is a pointer to a function, *pf is a function; hence, you should use (*pf)() as a function call. A second school maintains that because the name of a function is a pointer to that function, a pointer to that function should act like the name of a function; hence you should use pf() as a function call. C++ takes the compromise view that both forms are correct, or at least can be allowed, even though they are logically inconsistent with each other. Before you judge that compromise too harshly, reflect that the ability to hold views that are not logically self-consistent is a hallmark of the human mental process.

关于c - 对于函数指针 "fptr",为什么 "fptr"和*fptr的值相同?*fptr到底是什么意思?我只知道(*fptr)()或fptr(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16580411/

相关文章:

c - 这个宏在这种情况下如何工作?

c++ - C++中的动态库,插件框架和函数指针转换

c - 类型转换函数指针

c - glibc链接差异导致段错误

c - 是什么导致了堆栈溢出?我该如何解决它?

objective-c - 在 Objective-C 中如何加二?

c++ - 引用水平第 2 部分

c++ - 模板和函数指针

c# - 从 C++ 调用 C# 事件

c - 为什么我在尝试创建共享对象时收到 gcc "undefined reference"错误?