c - 函数指针的地址和函数指针的内容是一样的吗?

标签 c pointers function-pointers

<分区>

我试过这段代码

  1 #include <stdio.h>
  2
  3 int  sum(int a,int b)
  4 {
  5  printf ("\nFun sum called");
  6  return a+b;
  7 }
  8
  9 int main()
 10 {
 11  int a=5;
 12  int b=6;
 13  printf("\n 1. %d",sum(a,b));
 14  printf("\nAddress of sum : %p",&sum);
 15  int (*fptr)(int,int) = NULL;
 16  fptr = &sum;
 17  printf("\n 2. %d",fptr(a,b));
 18  printf("\nAddress of fptr is %p and fptr is %p",fptr,*fptr);
 19  return 1;
 20 }

我的输出是

 Fun sum called
 1. 11
 Address of sum : ***0x400498***
 Fun sum called
  2. 11
 ***Address of fptr is 0x400498 and fptr is 0x400498***

为什么函数指针的地址和函数指针内部地址所持有的内容看起来是一样的?

他们应该是不同的!我错过了什么吗?

最佳答案

fptr 不是这个变量的地址,它是这个变量的

由于您设置了 fptr = &sum,您实际上是在执行:

printf("\nAddress of sum is %p and sum is %p",&sum,sum);

事实上,表示函数的符号的地址和值是相同的。


值得注意的是,相同的行为适用于表示数组的符号。

这些符号(函数和数组)的共同点是它们是常量。

换句话说,一旦你声明了这样的符号,你就不能将它设置为不同的值。


如果你想比较地址和fptr的值,那么你应该执行:

printf("\nAddress of fptr is %p and fptr is %p",&fptr,fptr);

除非你设置fptr = &fptr,这肯定会打印两个不同的值。

关于c - 函数指针的地址和函数指针的内容是一样的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25847931/

相关文章:

c - 在 C 代码中使用 strcmp 时遇到问题

c - 为什么指向 16 位寄存器的指针是 uword?

c - 将参数从指针传递到非封闭地址空间时出错

更改函数指针的地址值

c - 为什么这个程序中printf的用法是错误的?

c++ - 在函数指针之间转换

c - 在节点中有多个元素的 B 树中递归查找第 k 个最小元素

c - 如何按升序创建链表

c++ - C++ | BST对节点指针的引用与节点指针

c - 将文件加载到 C 中的二维字符数组中