在C语言中,我可以通过堆栈指针访问另一个函数中的main函数的局部变量吗?

use*_*064 0 c stack gcc stack-pointer

我需要访问main函数中定义的变量a的值,而不将其作为参数传递.

main()
{
    int a=10;

    func();

    printf("%d\n",a);
}

void func(){
//i need access of variable a here.
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

jhk*_*9wx 5

您可以将指针传递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;
}
Run Code Online (Sandbox Code Playgroud)