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

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

问题描述

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

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.

我在 main 中尝试了索引和指针,但结果仍然相同.我该如何解决这个问题?

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 是返回给 main() 的函数 add5ToEveryElement() 中的本地数组.这是未定义的行为.

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

您至少可以更改此行:

int theArray[5];

到:

int *theArray = new int[5];

它会工作得很好.不要忘记稍后在 main() 中 delete 它.既然修改了原来的指针,就保存:

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天全站免登陆