读指针两次​​是给垃圾值 [英] Reading pointers twice is giving garbage values

查看:150
本文介绍了读指针两次​​是给垃圾值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过指向main函数的指针返回在局部函数中创建的数组。我的代码如下。返回数组,我能够通过元素一次访问每个元素。下一次它给垃圾值。什么是错误?

  void DoWork(int ** ppOut,int& nSize)
{
int m [5];
for(int i = 0; i <5; i ++)
{
m [i] = i;
}

nSize = 5;
cout<< m [0]< endl;
cout<< m [1]<< endl;
cout<< m [2] endl;
cout<< m [3]< endl;
cout<< m [4]< endl;

* ppOut =& m [0];

// delete [] m;
}

void main()
{
int nSize = -1;
int i;
int * f = NULL;

DoWork(& f,nSize);

cout<< f [3]< endl;
cout<< f [0]< endl;
cout<< f [2]< endl;
cout<< f [3]< endl;
cout<< f [4]< endl;

_getch();
}

输出为: - 0 1 2 3 4来自局部函数。
但是在main 3中,剩下的是grabage值

解决方案

问题: >
数组 m 是一个局部数组,它不在函数的生命周期内存在 DoWork()。当你这样做,你最终得到未定义的行为,这基本上意味着你可以看到任何可观察的行为,因为该程序不再是一个C ++标准批准的程序,所以它可以显示(



您将需要延长

的生命周期。 code> m ,以便它仍然有效,即使函数返回后。有很多方法可以做到这一点:




  • 在函数&

  • 在函数中使用动态内存作为数组。在使用后释放它)

  • 使用可以在函数内部划出的全局数组。





void main()不是 main()的标准指定原型,它应该返回 int

  int main()


I want to return an array created in a local function through pointers to the main function. My code is below. The array is returned and I am able to access each element by element once only. The next time it is giving garbage values. What is Wrong?

void DoWork(int** ppOut , int& nSize)
{
    int m[5];
    for(int i = 0 ; i < 5 ; i++)
        {
            m[i] = i;
        }

    nSize = 5;
    cout << m[0] << endl;
    cout << m[1] << endl;
    cout << m[2] << endl;
    cout << m[3] << endl;
    cout << m[4] << endl;

    *ppOut = &m[0];

    //delete [] m;
}

void main()
{
    int nSize = -1;
    int i;
    int* f = NULL; 

    DoWork(&f , nSize);

    cout << f[3] << endl;
    cout << f[0] << endl;
    cout << f[2] << endl;
    cout << f[3] << endl;
    cout << f[4] << endl;

    _getch();
}

Output is:-- 0 1 2 3 4 from local function. But in main 3 and rest are grabage values

解决方案

The Problem:
The array m is a local array which does not exist beyond the lifetime of the function DoWork(). When you do so what you end up with is Undefined Behavior, which basically means that you can see any observable behavior because the program ceases to be a C++ standard approved program and so it can show(literally) any behavior.

The Solution:
You will need to extend the lifetime of m so that it is still valid even after the function returns. There are number of ways to do this:

  • Create an array before the function & pass a pointer to it to the function.
  • Create a static array inside the function.
  • Use dynamic memory for the array in function (do remember to release it after usage)
  • Use global array which can be poulapted inside the function.

Each has own pros and cons and its more of horses for courses.

On a side note, void main() is not the standard specified prototype for main() it should return an int:

int main()

这篇关于读指针两次​​是给垃圾值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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