我需要访问在 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;
}
关于c - C语言中,可以通过栈指针访问另一个函数中main函数的局部变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46422668/