函数指针和一个函数的地址

问题描述:

所以我做函数指针的时候算了一下,你不需要运营商的放大器; 来获得初始函数的地址:

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\n",fun1(10));
    printf("%f\n",fun2(10));

    printf("fun1 = %p \t &foo = %p\n",fun1, &foo);
    printf("fun2 = %p \t  foo = %p\n",fun2,  foo);       

    int a[10];

    printf("  a = %p \n &a = %p  \n",a,&a);

    return 0;
}

输出:

>./a.out 
100.000000
100.000000
fun1 = 0x4004f4      &foo = 0x4004f4
fun2 = 0x4004f4       foo = 0x4004f4
  a = 0x7fff26804470 
 &a = 0x7fff26804470 

然后,我意识到这也是数组真,这意味着,如果你有 int类型的[10] 两者 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?

由于 int类型的[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 * 并指向数组的初始元素。 &放大器;一个的类型为 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.

功能类似于数组,但不完全一样的。你的函数的类型为双(双)。每当在离pression使用,而不是一元&放大器的操作; 运营商来说,隐式转换为指向自己的指针,它的类型的双(*)(双)

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).

因此​​,对于所有的实际目的,一个函数的名称和一个指向相同功能可以互换。有一些细微之处,所有这一切都在我的答案讨论\"Why做所有这些疯狂的函数指针的定义所有的工作?什么是真的吗?(这个问题被问及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.)