【发布时间】:2014-12-22 19:58:52
【问题描述】:
我是 C 初学者,一直在阅读一本名为“理解和使用 C 指针”的书,结果在使用 printf 函数时遇到了问题。
使用 debug_p 时,发现指针 num_p 的地址与 debug 中的 num 不同,但在 main() 中尝试 printf 时返回正确的值。
我的问题是,为什么会这样?是否有适当的方法在函数中执行 printf 并具有正确的指针地址?
#include <stdio.h>
void debug(int num)
{
printf("Address of num: %i Value: %i\n", &num, num);
}
void debug_p(int *num_p)
{
printf("Address of num_p: %i Value %i\n", &num_p, num_p);
}
int main()
{
int num=11;
int *num_p=#
printf("Address of num: %i Value: %i\n", &num, num);
printf("Address of num_p: %i Value: %i\n\n", &num_p, num_p);
debug(num);
debug_p(num_p);
return 0;
}
main() 的输出:
Address of num: 2358860 Value: 11
Address of num_p: 2358848 Value: 2358860
从调试输出,然后是 debug_p:
Address of num: 2358816 Value: 11
Address of num_p: 2358816 Value 2358860
【问题讨论】:
-
使用
%p打印变量的地址。 -
我给了你一个答案,但我不确定它是否涵盖了你的实际问题。你能改写一下吗?我愿意帮助你,但我不明白你的问题是什么。
-
我目前的问题是我不完全理解为什么 debug_p 中的 num_p 的值在调试时没有指向 num 的地址,但是在 main 中这样做就很好了。您的回答很清楚,但绝对不是很直观。
-
好的,我知道了。我会给你另一个答案,因为它实际上与我迄今为止回答的不同(尽管如此)。
-
函数内部的
num和num_p是副本,按值传递,与函数外部定义的变量不同。