在您的程序中,函数f(int a[]) 中只有一个小错误
void f(int a[]) {
printf("2.%x ", &a);
}
函数f返回函数参数的地址,而不是它指向的地址。
由于掌握 C 中的指针是理解 C 语言的基本方面之一,因此不仅
C 语言本身,但机器架构和 CPU/内存功能的基础知识。
因此,在指针算术和搜索/调试中出错甚至可以驱动
经验丰富的 C 程序员为之疯狂,毫不奇怪,他们在 C++ 中被利用
static_cast、dynamic_cast 关键字,并在随后的计算机语言中完全删除(隐藏,即..)。
所以,我更进一步,重新编写了您的代码,更好地解释了该错误。
#include <stdio.h>
void f(int b[]) {
printf("\n func call. print address: %x", &b); }
void f2(int b[]) {
printf("\n func call. print address(2): %x", b); }
int main()
{
int *j, a[11];
j = a; // load address of 'a' array to int pointer 'j'
// pointer 'j'
// j = address of an array 'a'
// &j = address of 'j' !!
*j = 1; // value of any 'int' that 'j'
// points to is 1,so the value
// of a[0]= 1
// ______ print values of 'j', 'a' ______
// value is from address 'a'
printf("\n1.) value of number (j)= %d", *j);
// int value of address 'a'
printf("\n1.) value of number (a)= %d", a[0]);
// ______ print addresses of 'j', 'a' ______
// address of int variable 'j' that
// holds pointer to 'a'
printf("\n\n2.) addr of number (j)= %x", &j);
// address of 'a' array
printf("\n2.) addr of number (a)= %x", &a);
// ______ all of following adressess are the same ______
// actual pointer (points to 'a' now)
printf("\n\n3.) addr of 'j' = %x", j);
// address od an array 'a'
printf("\n3.) addr of 'a' = %x", a);
// address of first int member in array a
printf("\n3.) addr of 'a[0]'= %x\n", &a[0]);
// ______ print them from function ______ (yours) ..
f(&j); f(a); // outputs an address of an argument passed to a function !!!
// ______ print them from function ______ (changed) ..
f2(&j); f2(a); // outputs an address that an argument points to !!
// (holds address of)
return 0;
}
函数f 和f2 中的int b[] 是有意 而不是int a[],因此很明显,参数是压入堆栈的变量的副本 - 不是实际变量 a.
程序输出:
1.) value of number (j)= 1
1.) value of number (a)= 1
2.) addr of number (j)= 5f826328
2.) addr of number (a)= 5f826330
3.) addr of 'j' = 5f826330
3.) addr of 'a' = 5f826330
3.) addr of 'a[0]'= 5f826330
func call. print address: 5f826308
func call. print address: 5f826308
func call. print address(2): 5f826328
func call. print address(2): 5f826330