修改函数中的指针值 [英] Modify pointer value in a function
问题描述
我正在研究指针,并试图理解这段代码.
I'm studying pointers and i'm trying to understand this code.
int main()
{
int i=66 ;
int *x;
x=&i;
f(&x);
printf("%d",*x);
return 0;
}
void f(int *x)
{
int j=7;
x=&j;
printf("%d-",*x);
}
我期望输出: 7-7 ,但我得到 7-66.我想当我写
I'm expectin as output : 7-7 , but i get 7-66. I suppose that when i write
x=&j;
在函数中,原始指针现在被设置为 j 值的方向,这是可以的,因为 printf 返回 7- 但是为什么当我回到 main 时, printf 返回 66?指针现在不是设置为函数的 j 值吗?我知道关闭函数时函数中的值会丢失,但是为什么我的指针在运行函数后仍然设置为主函数中的 i 值?
in the function the original pointer now is setted to the direction of the j value and this is ok because the printf return 7- but why when i go back to the main the printf return 66? isn't the pointer now setted to the j value of the function ? i know the values in the function are lost when i close the function but why my pointer is still setted to the i value in the main after i run the function?
推荐答案
在您的函数 f(int* x)
中,您将变量 x
分配给地址您的本地临时变量 j
.您真正想要做的是将 x
指向的 value 分配给 j 的 value.
In your function f(int* x)
, you are assigning the variable x
to the address of your local, temporary variable j
. What you really want to do is assign the value of what is pointed to by x
to the value of j.
#include <stdio.h>
#include <stdlib.h>
void f(int *x)
{
int j=7;
*x=j;
printf("%d-",*x);
}
int main()
{
int i=66 ;
int *x;
x=&i;
f(x);
printf("%d",*x);
return 0;
}
这可以在这里运行.
第二个问题是,您在主函数中获取变量 x
的地址,并将其作为参数传递给 f(int*)
,后者变为指向 int 指针的指针(int**
而不是 int*
).请记住,x
已经是一个 int*
并且可以直接传递.
A second issue is the fact that you take the address of your variable x
in the main function and pass that as a parameter to f(int*)
which becomes a pointer to a pointer to an int (an int**
not an int*
). Remember that x
is already an int*
and can be passed directly.
这篇关于修改函数中的指针值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!