由全局指针引用的局部变量

时间:2014-06-08 05:48:14

标签: c

我在这里有一个问题。我有以下代码

#include <stdio.h>
int *ptr;

int myfunc(void);
main()
{
   int tst = 3;
   ptr = &tst;
   printf("tst = %d\n", tst);
   myfunc();
   printf("tst = %d\n", tst);
}

int myfunc(void)
{
    *ptr = 4;
}

局部变量存储在堆栈中。我创建了一个全局指针* ptr并使其指向main中的局部变量。现在,当我调用myfunc时,main的局部变量被推送到堆栈上。在myfunc中,我改变了指针的值,在返回main之后,我检查了现在已经改变的局部变量的值。 我想问一下,在myfunc中,推送的变量tst再次被poped它的值被改变了吗?我几乎是初学者,所以请不要介意。

3 个答案:

答案 0 :(得分:2)

不,tst不是&#34;弹出&#34;再次。 myfunc只接收tst位于堆栈中的地址,并更新该地址的内存。

注意,指向自动(堆栈)变量并将它们放在全局变量中通常是一个坏主意。函数退出后指针停止有效,但系统不会检测到,因此可能存在内存损坏。在这种情况下不是问题,但也不是一个良好的习惯。

答案 1 :(得分:0)

由于ptr是全局的,当你指向某个函数内的某个对象时,它会全局指向该对象的内存位置。

您正在myfunc()更新该内存位置的内容,然后访问main()中的相同内存位置。很明显,您在myfunc()中所做的更改是可见的。

答案 2 :(得分:0)

当进行函数调用时,并非所有变量都被压入堆栈。只有那些作为函数参数的东西才会被压入堆栈,即括号中的那些,如:myfunc(arg);。在这种情况下,arg将被推送到堆栈以供myfunc使用。关键是要记住在C中它只是被推送的变量中的值,而不是变量本身。

你可能会追求这样的事情

#include <stdio.h>
int *ptr;

int myfunc(int value);
int myfunc2(int *pValue);

main()
{
   int tst = 3;
   ptr = &tst;
   printf("tst = %d\n", tst);
   myfunc(*ptr);
   printf("tst = %d\n", tst);
   myfunc2(ptr);
   printf("tst = %d\n", tst);
}

void myfunc(int value)
{
    //here you can do whatever you want with the value that was in the global ptr
    //but when you return to main it will not have changed.

    value = value + 10;       //has no effect on tst
}

void myfunc2(int *pValue)
{
    //here the argument is a pointer value. If you de-reference the pointer value
    //with an '*' you start accessing the contents at that address

    *pValue = *pValue + 10;    //does effect the global *ptr
}
相关问题