问题描述
所以我想在制作函数指针时,不需要operator &
来获取初始函数的地址:
So I figured when making function pointers, you do not need the operator &
to get the address of the initial function:
#include <stdio.h>
double foo (double x){
return x*x;
}
int main () {
double (*fun1)(double) = &foo;
double (*fun2)(double) = foo;
printf("%f
",fun1(10));
printf("%f
",fun2(10));
printf("fun1 = %p &foo = %p
",fun1, &foo);
printf("fun2 = %p foo = %p
",fun2, foo);
int a[10];
printf(" a = %p
&a = %p
",a,&a);
return 0;
}
输出:
>./a.out
100.000000
100.000000
fun1 = 0x4004f4 &foo = 0x4004f4
fun2 = 0x4004f4 foo = 0x4004f4
a = 0x7fff26804470
&a = 0x7fff26804470
然后我意识到对于数组也是如此,这意味着如果你有 int a[10]
a
和 &a
指向同一个位置.为什么是数组和函数?地址是否保存在与保存在其中的值(地址)具有相同地址的内存位置?
Then I realized this is also true for arrays, meaning that if you have int a[10]
both a
and &a
point to the same location. Why is that with arrays and functions? Is the address saved in a memory location that has the same address as the value(address) being saved in it?
推荐答案
Given int a[10]
, a
和 &a
> 产生相同的地址,是的,但它们的类型不同.
Given int a[10]
, both a
and &a
yield the same address, yes, but their types are different.
a
是 int[10]
类型.隐式转换为指针类型时,指针为int*
类型,指向数组的初始元素.&a
是 int (*)[10]
类型(即指向十个整数数组的指针).因为数组中不能有填充,它们都产生具有相同值的指针,但指针具有不同的类型.
a
is of type int[10]
. When it is implicitly converted to a pointer type, the pointer is of type int*
and points to the initial element of the array. &a
is of type int (*)[10]
(that is, a pointer to an array of ten integers). Because there can be no padding in an array, they both yield pointers with the same value, but the pointers have different types.
函数类似于数组,但并不完全相同.你的函数 foo
是 double(double)
类型.每当在表达式中使用 foo
并且不是一元 &
运算符的操作数时,它都会隐式转换为指向自身的指针,类型为 double(*)(double)
.
Functions are similar to arrays, but not entirely the same. Your function foo
is of type double(double)
. Whenever foo
is used in an expression and is not the operand of the unary &
operator, it is implicitly converted to a pointer to itself, which is of type double(*)(double)
.
因此,出于所有实际目的,函数名和指向同一函数的指针是可以互换的.有一些微妙之处,我在对 为什么所有这些疯狂的函数指针定义都有效?到底发生了什么?"(这个问题是关于 C++ 的,但 C++ 中非成员函数的规则是与 C 中的函数相同.)
So, for all practical purposes, the name of a function and a pointer to the same function are interchangeable. There are some subtleties, all of which I discuss in an answer to "Why do all these crazy function pointer definitions all work? What is really going on?" (That question was asked about C++, but the rules for nonmember functions in C++ are the same as for functions in C.)
这篇关于函数指针和函数地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!