注册 登录
编程论坛 C++教室

此程序为什么得不到期望值20和4435500??大神们,求分析?????????

芦苇太帅了 发布于 2013-08-23 13:00, 633 次点击
#include<iostream.h>

int * getInt(char * str)
{
    int value=20;c
    cout<<str<<endl;
    return &value;
}

void somefn(char * str)
{
    int a=40;
    cout<<str<<endl;
}

int main()
{
    int * pr=getInt("input a value:");
    cout<<* pr<<endl;
    somefn("It is uncertain.");
    cout<<* pr<<endl;
}

5 回复
#2
peach54602013-08-23 15:06
指针没玩熟
#3
lzj125302013-08-24 08:31
#include<iostream.h>

 int * getInt(char * str)
 {
     int value=20;c  //函数内部的变量,也就是局部变量,他的作用只能在本函数内部.
     cout<<str<<endl;
     return &value; //返回指向这个value,但是函数结束时,这个变量被销毁。内容不确定,内存泄露
 }

 void somefn(char * str)
 {
     int a=40;
     cout<<str<<endl;   //a变量更无半毛钱关系
 }

 int main()
 {
     int * pr=getInt("input a value:");
     cout<<* pr<<endl;
     somefn("It is uncertain.");
     cout<<* pr<<endl;
 }
#4
love云彩2013-08-24 08:42
如楼上所说的正确,我也不知道你想要的4435500是什么来的。
程序代码:
#include<iostream>
using namespace std;

 int value=20;//改为全局变量就可以了
int * getInt(char * str)
{
  

    cout<<str<<endl;
    return &value;
}

void somefn(char * str)
{
    cout<<str<<endl;
}

int main()
{
    int * pr=getInt("input a value:");
    cout<<* pr<<endl;
    somefn("It is uncertain.");
    cout<<pr<<endl;//这里输出pr的地址值
    return 0;
}

#5
peach54602013-08-24 19:48
2L说得很好,我懒得打那么多字
#6
芦苇太帅了2013-08-25 13:14
二楼是对的,这个程序应返回一个局部变量的的地址而出错。
   大婶们,谢谢指导!
1