我需要访问在 main 函数中定义的变量 a 的值,而不将其作为参数传递。
main()
{
int a=10;
func();
printf("%d\n",a);
}
void func(){
//i need access of variable a here.
}
我怎样才能做到这一点?
您可以将指针传递给a
到你的函数。只要相应的局部变量存在,指向局部变量的指针就有效。
所以
#include <stdio.h>
void func(int *ptr);
main()
{
int a = 10;
// Pass pointer to a
func(&a);
printf("%d\n", a); // Prints 12
}
// function accepts pointer to variable of type int
void func(int *ptr)
{
// update value behind the pointer
*ptr = 12;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)