因此,我将变量的地址传递给特定的函数。我使用函数内部的指针更改了变量的值,当我在函数中打印变量时,会反映该更改。但是当我在调用函数后在 main() 块中打印它时,它并没有反映相同的值。
#include<stdio.h>
int main()
{
int result_count;
int* result = waiter(n, number, q, &result_count);
printf("%d",result_count); //prints 0
}
int* waiter(int number_count, int* number, int q, int* result_count)
{
int t=10;
result_count=&t;
printf("\n%d",*result_count); //prints 10
}
这就是代码,我尝试将“t”的值分配给“result_count”,但在主块中,该值打印为 0 或只是一个随机数。
因为参数
result_count
是函数waiter()
的局部变量。它的值的任何变化都会反映在 waiter()
函数体内。result_count
变量所保存的变量的值,则取消引用它并赋值:
*result_count = t;
取消引用
result_count
意味着您的程序正在访问其地址result_count
指针变量所保存的变量的内存。
最初当调用
waiter()
函数时,指针result_count
指向传递给waiter()
的参数内存:
result_count 100
+-----+ +-----+
| 100 |------------>| |
+-----+ +-----+
After this statement -
result_count=&t;
waiter() main()
result_count result_count (assume it's address is 100)
+-----+ +-----+
| 200 |----+ | |
+-----+ | +-----+
|
| waiter()
| t (assume it's address is 100)
| +-----+
+------->| |
+-----+