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

标签 c gcc stack stack-pointer

我需要访问在 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/

相关文章:

c - 可以在函数内部运行一个 c 数组,只用一个指针作为参数吗?

C |套接字不接受通过 telnet 的连接

c++ - 使用 g++ 编译多个 .cpp 和 .h 文件。我做对了吗?

windows - 如何在 Windows 上获取线程堆栈信息?

c++ - Windows Vista+ IFileOpenDialog 和大堆栈的内存问题

C 相邻堆栈寻址

c - 大数组导致段错误

c - 如何编写读取用户输入字符串并仅打印非 ‘a-z’ 或 ‘A-Z’ 的 C 程序

c++ - 有没有解决使用STL对用户输入数组进行排序的错误的解决方案?

c++ - 在 gcc 中编译时出错