函数名本身就是这个函数的起始地址?为什么取函数名的地址后还是这个结果?

drinker_linux 2009-06-25 10:23:15
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void test()
{
printf("123456\n");
}

int main(int argc, char *argv[])
{
printf("0x%x\n",test);
printf("0x%x\n",&test);
}

[root@localhost pht]# ./a.out
0x8048328
0x8048328

我非常的困域
这两个printf的结果怎么会一样呢?求大侠解答
printf("0x%x\n",test);
printf("0x%x\n",&test);
...全文
928 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
青岛芒果 2009-06-25
  • 打赏
  • 举报
回复
函数名跟数组名一样,都是表示地址常量的。所以func, &func都是一回事。本来不该写成&func的形式。
drinker_linux 2009-06-25
  • 打赏
  • 举报
回复
多谢各位的指点,在下略懂一二了。谢谢
a_p_z 2009-06-25
  • 打赏
  • 举报
回复
C++ primer关于函数指针那章曾经写过
func 和 &func 其实是一回事
历史问题,习惯问题,写法问题,兼容问题
其实自己动脑想想,函数只存在入口地址概念,本身无取值的概念
飞天御剑流 2009-06-25
  • 打赏
  • 举报
回复
[Quote=引用楼主 drinker_linux 的帖子:]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void test()
{
printf("123456\n");
}

int main(int argc, char *argv[])
{
printf("0x%x\n",test);
printf("0x%x\n",&test);
}

[root@localhost pht]# ./a.out
0x8048328
0x8048328

我非常的困域
这两个printf的结果怎么会一样呢?求大侠解答
printf("0x%x\n",test);
printf("0x%x\n",&test);
[/Quote]

按照&运算符本来的意义,它要求其操作数是一个对象,但函数名不是对象(函数是一个对象),本来&test是非法的,但很久以前有些编译器已经允许这样做,c/c++标准的制定者出于对象的概念已经有所发展的缘故,也承认了&test的合法性。

因此,对于test和&test你应该这样理解,test是函数的首地址,它的类型是void (),&test表示一个指向函数test这个对象的地址,它的类型是void (*)(),因此test和&test所代表的地址值是一样的,但类型不一样。test是一个函数,&test表达式的值是一个指针!

跟此问题类似的还有对一个数组名取地址。

标准在其rationale中解释了这个问题,摘录如下:

6.5.3.2 Address and indirection operators

Some implementations have not allowed the & operator to be applied to an array or a function.
(The construct was permitted in early versions of C, then later made optional.) The C89 Language
Committee endorsed the construct since it is unambiguous, and since data abstraction is
enhanced by allowing the important & operator to apply uniformly to any addressable entity.
localxiao 2009-06-25
  • 打赏
  • 举报
回复
参考指针和数组名的区别
drinker_linux 2009-06-25
  • 打赏
  • 举报
回复
请问意义有何不同?
nlylidb 2009-06-25
  • 打赏
  • 举报
回复
内容相同不代表意义相同

#include <stdio.h>
int main(void)
{
int a[10];
printf("%p\n", a);
printf("%p\n", &a);
return 0;
}
foxyz123 2009-06-25
  • 打赏
  • 举报
回复
函数名并不能等同于指针,如果是指针,

p代表其所指向的首地址
&p表示保存指针变量的地址

函数名在使用上是和指针等同,但其并非是一个真正的指针,就象数组名一样一样的,所以你用test和&test所指向的地址是一样的,都是数据的首地址

70,020

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧