我需要访问在 main 函数中定义的变量 a 的值,而不将其作为参数传递。
main()
{
int a=10;
func();
printf("%d\n",a);
}
void func(){
//i need access of variable a here.
}
我怎样才能做到这一点?
我需要访问在 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;
}
你不能这样做,因为那个变量可能甚至不存在然后func()
被调用。在您的示例中,编译器很可能会对其进行优化并有效地创建以下代码:
main()
{
func();
printf("%d\n",10);
}
如果您确定变量没有被优化,它很可能存储在某个寄存器中。该寄存器,如果您知道它是哪一个,则可能可以从中访问func()
或存储在堆栈中。但是,如果您确定它a
实际上是在堆栈帧中分配的,则main()
可以在堆栈中向下挖掘,搜索指向main()
并访问main()
. 但是您仍然不知道a
堆栈帧中的位置。
不,因为每个局部变量都被压入相应函数的堆栈帧中,并且每个函数只能使用当前帧指针访问自己的堆栈帧。
注意:这对 ARM GCC 9.2.1 有效
如果这是一个纯粹的理论问题(如评论中所建议的),答案可能是将指针存储a
在全局变量中。(尽管我无法想出该解决方案具有任何实际好处的任何现实世界场景)。
static int *ptr;
main()
{
int a=10;
ptr=&a;
func();
printf("%d\n",a);
}
void func(){
// update value behind the pointer
*ptr=12;
}
局部变量存储在堆栈中,并且将在堆栈中具有地址。我们可以做的是通过改变堆栈指针地址开始检查它,直到你得到与局部变量相同的地址,然后你可以对其进行所需的操作。当然,这不是 c 编程的正确方法,但这是唯一的方法。下面是代码。
注意:值 TriedAndTested 取为 13,因为我在将堆栈指针递增 13 次后得到了地址。在其他编译器中可能会有所不同。相反,人们可以比较地址,然后对其进行评估。
#include<stdio.h>
#define TriedAndTested 13 //keep incrementing until you get the value of a
void func(){
void *p=NULL;
int *st;
int i=0;
st=(void *)&p;
printf("p is %ld\n",st);
for(i=0;i<TriedAndTested;i++){
st++;
printf("p is %ld\n",*st);}
printf("p is %ld\n",++(*st)); //here i am incrementing the value of a
}
int main(){
int a = 89; //trying to change the value of a in func()
func();
printf("%ld -> %d\n",&a,a);
return 0;
}