Here is a very simple program. It basically consists of three different files.
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include "./RandomHashes.h"
using namespace std;
int main(int argc, char* argv[])
{
int a=6848;
int *p;
cout << *p << endl;
assignRandomValue(p);
cout << *p << endl;
p++;
assignRandomValue(p);
cout << *p << endl;
return 0;
}
| |
RandomHashes.h
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#ifndef RANDOM_HASHES
#define RANDOM_HASHES
// Header protection
#endif
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cmath>
void assignRandomValue(int*);
| |
RandomHashes.cpp
1 2 3 4 5 6 7
|
#include "./RandomHashes.h"
void assignRandomValue(int* addr)
{
srand(time(NULL));
*addr = rand();
}
| |
And here is the output...
Now, I know that the first
in the output is basically the initial value of the cell that pointer points to. And I know, the second
23804
is the random number assigned by function
assignRandomValue(p)
to the cell that
p
points to.
But the third
23804
, shouldn't that be some other number?
I have possible explanations:
1- This might be by chance. Since the rand function assigns a random value to the variable and doesn't care if that value has or hasn't been assigned to any previous variable in the same program. If this was the case, the problem could be rectified simply by running the program once again. But I have executed the program again and again and although the value of the first cell changes every time, the value of the second cell is alway equal to the first one.
2- Another explanation is, maybe I am printing the same cell again and again. So, I went back to the
main()
and in lines 9, 11 and 13, removed the '*' from before the variable a.k.a 'p' so that the program will now print the addresses of the cells instead of the values. And the output indicated that the pointer is indeed getting incremented, pointing to the next integer cell in the memory (an increment of 4-bytes in the address)...
3- There is another possible explanation, which I am not sure if really is an explanation. But is this possible, that the since the random function is seeded by the current time, the value returned by
time(NULL)
hasn't changed yet while the main function calls for assignment to the next cell? In other words, the random function "calculates" the same value for both the cells because seed is same for both values? If this is possible, what is the workaround.
And I am not that proficient with C++, so I might be terribly wrong with the explanations or doing some stupid mistake somewhere that I am looking over.
Could anyone please point out the problem here?