vendredi 3 février 2017

Having trouble printing out the first two numbers in a dynamically allocated array, the other numbers work fine

#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.




Aucun commentaire:

Enregistrer un commentaire