C语言 全局指针引用的局部变量

9fkzdhlc  于 2023-02-03  发布在  其他
关注(0)|答案(3)|浏览(222)

我有一个问题。我有以下代码

#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中,我更改了ptr的值,并在返回main后,我检查现在已更改的局部变量的值。
myfunc中,是否再次弹出压入变量tst以更改其值?

6pp0gazn

6pp0gazn1#

不,tst不会再次“出栈”。myfunc只是接收tst在堆栈中所处的地址,并在该地址更新内存。
请注意,将指针指向自动(堆栈)变量并将它们放在全局变量中通常是个坏主意。函数一退出,指针就不再有效,但系统不会检测到这一点,因此内存可能会损坏。在这种情况下不是问题,但也不是一个好习惯。

qoefvg9y

qoefvg9y2#

当一个函数被调用时,并不是所有的变量都被压入栈中,只有那些作为函数参数的变量才会被压入栈中,即:括号中的数字,像这样:myfunc(arg);。在这种情况下,arg将被压入堆栈,以便在myfunc中使用。关键是要记住,在C中,压入的只是变量中的值,而不是变量本身。
你可能在找这样的东西

#include <stdio.h>
int *ptr;

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

int 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
}
uxhixvfz

uxhixvfz3#

因为ptr是全局的,所以当你让它指向函数内部的某个对象时,它会全局地指向那个对象的内存位置。
您正在更新myfunc()中该内存位置的内容,然后访问main()中的相同内存位置,因此显然您在myfunc()中所做的更改是可见的。

相关问题