-1
#include <iostream>
#include<cstdlib>
#include<ctime>

using namespace std;

int* randomNumbers(int min, int max, int size);
int main()
{
    int min = 20;
    int max = 100;
    int size = 10;
    int* nums; 

    nums = randomNumbers(min,max,size); 
    cout << "***************"<<endl;

    for(int i = 0; i < size;i++)
    {
        cout << *(nums+i) << endl; 
    }


    return 0;

}


int* randomNumbers(int min, int max, int size)
{
    int* random = new int[size]; 
    unsigned seed = time(0); //time elapsed since Jan 1, 1970
    srand(seed);

    for (int i = 0;i<size;i++)
    {
        *(random+i) = rand() % ((max+1)-min) + min;
        cout<<*(random+i)<<" ";

    }

     cout<<endl;

    delete[] random; 
    return random;
}

So if I run this code in Xcode(Macbook), it works perfectly, however if I run this in Codeblocks(Windows) , the first two numbers printed from the main function are in the millions but the first two numbers printed from the randomNumbers() are within expected range. I don't understand why printing the numbers in the main function is changing the first two values? The rest are fine. I'm really inarticulate, feel free to ask questions on my question.

Nahian Afsari
  • 41
  • 1
  • 4

1 Answers1

0
   delete[] random; 
   return random;

You are deleting your array!

Any access to your array after deleting it is Undefined. Clean up the array when you are done with it.

Move the delete here:

 for(int i = 0; i < size;i++)
 {
     cout << *(nums+i) << endl; 
 }

 delete[] nums;
 return 0;
user3853544
  • 581
  • 3
  • 9