9.5 查找地址:&运算符
指针(pointer)是C语言最重要的(有时又是最复杂的)概念之一,用于存储变量的地址。概括地说,如果主调函数不使用return返回的值,则必须通过地址才能主调函数中的值。
一元&运算符给出变量的存储地址。可以把地址看作是变量在内存中的位置。
PC地址通常用十六进制形式表示。
%p是输出地址的转换说明。
/* loccheck.c -- checks to see where variables are stored */
#include <stdio.h>
void mikado(int); /* declare function */
int main(void)
{
int pooh = 2, bah = 5; /* local to main() */
printf("In main(), pooh = %d and &pooh = %p\n",
pooh, &pooh);
printf("In main(), bah = %d and &bah = %p\n",
bah, &bah);
mikado(pooh);
return 0;
}
void mikado(int bah) /* define function */
{
int pooh = 10; /* local to mikado() */
printf("In mikado(), pooh = %d and &pooh = %p\n",
pooh, &pooh);
printf("In mikado(), bah = %d and &bah = %p\n",
bah, &bah);
}
/* 输出:
*/
实现不同,%p表示地址的方式也不同。然而,许多实现都如本例所示,以十六进制显示地址。顺带一提,每个十六进制对应4位。
该例输出说明:
首先,4个变量的地址不同,说明计算机把它们看成4个独立的变量。
其次,函数调用mikado( pooh )把实际参数的值传递给形式参数。注意,这种传递只传递了值。涉及的两个变量并未改变。
强调第2点,是因为这并不是在所有语言中都成立。例如FORTRAN中的子例程会影响主调例程的原始变量。在C语言中,每个C函数都有自己的变量。这样做更可取,因为这样做可以防止原始变量被被调函数的副作用意外修改。然而,这也带来了一些麻烦。下节讲述。