Implement a function which returns a pointer to some memory containing the integer 5

int* getPtrToFive()
{
  int* x = new int;
   *x = 5;
   return &x;    
}

void main()
{
    int* p = getPtrToFive();
    cout<<*p<<endl;    
    delete p;    
}

从MIT 公开课的一个课件看到的。 如果在 getPtrToFive里面不用指针,只是让 x = 5; return &x 那么在main函数里面将无法返回5这个值,因为变量定义域的问题。

posted @ 2013-11-26 23:57  LevyFan  阅读(100)  评论(0编辑  收藏  举报