0

cube of Randomly generated values which is not happeneing if I return the value from the main function.If I don't return it in the main function and print it in the user defined function then it is working properly. Where I have used pointers its mandatory.

#include<iostream>
#include<ctime>
using namespace std;



int* cube(int* ar)
{
    int re[50];
    for (int i = 0; i < 50; i++)
    {
        re[i] = *(ar + i) * *(ar + i)* *(ar + i);

    }
    return re;
}


int main()
{
    srand(time(NULL));
    int ar[50],
        cub[50];
    for (int i = 0; i < 50; i++)
    {
        ar[i] = (rand() % (99 - 50)) + 50;

    }
    int *ptr;
    cout << "Sr.#\tValue\tCube\n";
    ptr = cube(ar);  // this receives the value being returned from the function
    for (int i = 0; i < 50; i++)
    {
        cout << i << '\t' << ar[i] << '\t' << *(ptr + i) << endl;
    }
    return 0;
}
  • 1
    What is your question? Clarify the problem and include any error message or issue you're facing. – Omid Jun 02 '20 at 04:36

1 Answers1

1

It is a bad idea to return pointers or references to local variables. replace

int re[50];

with

int* re=new int[50];
Hikmat Farhat
  • 552
  • 3
  • 9