指向C ++中的局部变量的指针 [英] Pointer to local variable in C++

查看:203
本文介绍了指向C ++中的局部变量的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
能否在其范围之外访问局部变量的内存? /a>

Possible Duplicate:
Can a local variable's memory be accessed outside its scope?

我在C ++中具有以下代码

I have the following code in C++

int* foo()
{
    int myVar = 4;
    int* ptr = &myVar;
    return ptr;
}

int main()
{
   printf("val= %d", *foo());
   return 0;
}

我得到的输出是:

val = 4

所以我的问题是因为myVar是局部变量,函数返回后不应该消失吗?并且指向它的指针也不应该也为空指针吗?

So my question is since myVar is a local variable, shouldn't it be gone after the function returns? and shouldn't the pointer to it be a null pointer as well?

推荐答案

在您的情况下,printf("val= %d", *foo())正在打印垃圾值.由于没有其他代码,因此该数据尚未更改.

In your case, printf("val= %d", *foo()) is printing the garbage value. As there is no other code, that data has not been changed.

运行此代码,您将获得想法

You run this code, you will get the idea

    int* foo() 
    { 
        int myVar = 4; 
        int* ptr = &myVar; 
        return ptr; 
    } 

    int* foo1() 
    { 
        int myVar = 5; 
        int* ptr = &myVar; 
        return ptr; 
    } 
    int main() 
    { 
        int* x = foo();
        int* x1 = foo1();
       printf("val= %d", *x); 
       return 0; 
    } 

这篇关于指向C ++中的局部变量的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆