函数返回数组,但主要显示垃圾 [英] Function returning array but main showing garbage

查看:122
本文介绍了函数返回数组,但主要显示垃圾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是打印垃圾值。我将一个数组传递给一个函数,该函数向每个元素添加5,但是当它返回数组的指针时,主要显示垃圾。



我已经尝试了索引和指标在主要但仍然相同的结果。如何解决这个问题?

  #include< conio.h> 
#包含< iostream>
使用namespace std;

int * add5ToEveryElement(int arr [],int size)
{
int theArray [5];
for(int i = 0; i< size; i ++)
{
theArray [i] = arr [i] + 5;
cout<< theArray [i]<< endl;
}
返回theArray;
}

void main()
{
const int size = 5;
int noArr [size];
for(int i = 0; i< size; i ++)
{
noArr [i] = i;
}
int * arr = add5ToEveryElement(noArr,size);
cout<< endl;; cout<< endl; (int i = 0; i< size; i ++)
{
cout<< arr [i]<< endl;
}
cout< ltl; endl; cout<< endl; cout<< endl;; cout<< endl;
for(int i = 0; i< size; i ++)
{
cout<<< * arr<< endl;
* arr ++;
}
getch();


解决方案

theArray 是您返回到main()的函数 add5ToEveryElement()中的本地数组。这是未定义的行为。



最小化您可以更改此行:

  int theArray [5]; 

到:

  int * theArray = new int [5]; 

它可以正常工作。不要忘记稍后在main()中删除 delete 。保存它:

  int * arr = add5ToEveryElement(noArr,size); 
int * org = arr;
//其余代码

//最后

delete [] org;


The following code is printing garbage values. I am passing an array to a function which adds 5 to every element, but when it returns that array's pointer, the main is showing garbage.

I have tried both indexing and pointers there in main but still same results. How can I fix this?

# include <conio.h>
# include <iostream>
using namespace std;

int * add5ToEveryElement(int arr[], int size)
{
    int theArray[5];
    for(int i=0; i<size; i++)
    {
        theArray[i] = arr[i] + 5;
        cout<<theArray[i]<<endl;
    }
    return theArray;
}

void main()
{
    const int size = 5;
    int noArr[size];
    for(int i=0; i<size; i++)
    {
        noArr[i] = i;
    }
    int *arr = add5ToEveryElement(noArr, size);
    cout<<endl;cout<<endl;
    for(int i=0; i<size; i++)
    {
        cout<<arr[i]<<endl;
    }
    cout<<endl;cout<<endl;cout<<endl;cout<<endl;
    for(int i=0; i<size; i++)
    {
        cout<<*arr<<endl;
        *arr++;
    }
    getch();
}

解决方案

theArray is a local array in the function add5ToEveryElement() which you are returning to main(). This is undefined behaviour.

Minimally you can change this line:

int theArray[5];

to:

int *theArray = new int[5];

It'll work fine. Don't forget to delete it later in main(). SInce you modify the original pointer, save it:

int *arr = add5ToEveryElement(noArr, size);
int *org = arr;
// Rest of the code

//Finally

 delete[] org;

这篇关于函数返回数组,但主要显示垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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