0

I am new to c++. I wrote a function which returns a random array, but when I ran this function in a for loop, this only give the same array. Please help me.

#include <iostream>
#include<headers.h>
#include<cstdlib>
#include <ctime>
#include<stdlib.h>
#include<math.h>

using namespace std;

int * getRandom( ) {
        static int  r[8];
        int inicio = 0;
        int fin = 7;
        // set the seed
        srand( (unsigned)time( NULL ) );

        for (int i = 0; i < 8; ++i) {
                r[i] = rand()%8;
        }

        return r;
}
int main()
{
        int *r;
        r = getRandom();
        int *p = NULL;

        for(int i=0; i<10; i++){
                p = getRandom();
                cout<<"--------"<<endl;
                for(int j=0; j<8; j++){
                        cout<<p[j];
                }
                cout<<endl<<"--------"<<endl;
        }

        return 0;
}

this is the execution

Mode77
  • 991
  • 8
  • 28
  • This is a good time to learn [how to debug your programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/), especially how to do [rubber duck debugging](https://en.wikipedia.org/wiki/Rubber_duck_debugging). – Some programmer dude Nov 03 '18 at 03:49
  • 2
    Here's a hint: How many times to you *reset* the seed (to the same value!)? – Some programmer dude Nov 03 '18 at 03:49
  • If you're new to C++, please consider this: *none* of your standard headers should end in `.h`. There are C-wrap equivalencies . ex: `stdio.h` in C is `cstdio` in C++. Second, investigate the [``](https://en.cppreference.com/w/cpp/header/random) library of modern C++. It is the cats whiskers, and orders of magnitude more evolved and flexible than `srand/rand` hoops. – WhozCraig Nov 03 '18 at 03:55

1 Answers1

1

You called srand function multiple times.

srand returns the integer which seconds elapsed after 0:00:00 UTC, January 1st, 1970. Which means that, if the srand function is called multiple times in a second (of course UTC second), it will returns the same value.

Check it using this.

for(int i = 0; i < 10; i++) printf("%u\n", (unsigned int )time(NULL));

Hence, your code should be changed as below.

#include <iostream>
#include<cstdlib>
#include <ctime>
#include<stdlib.h>
#include<math.h>

using namespace std;

int * getRandom() {
    static int  r[8];
    int inicio = 0;
    int fin = 7;
    // set the seed
    for (int i = 0; i < 8; ++i) {
        r[i] = rand() % 8;
    }

    return r;
}

int main()
{
    int *r;
    srand((unsigned)time(NULL)); // srand function call should be placed here.
    r = getRandom();
    int *p = NULL;

    for (int i = 0; i < 10; i++) {
        p = getRandom();
        cout << "--------" << endl;
        for (int j = 0; j < 8; j++) {
            cout << p[j];
        }
        cout << endl << "--------" << endl;
    }
}

For more information, check here.

paganinist
  • 150
  • 1
  • 9