-8
int * getRandom( )
{
  static int  r[10];

  // set the seed
  srand( (unsigned)time( NULL ) );
  for (int i = 0; i < 10; ++i)
  {
    r[i] = rand();
    cout << r[i] << endl;
  }
  return r;
}

I want to know in this there is a function which is named as getRandon and the data type of this function is int. why we have declared this functions as a pointer.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • 2
    Unrelated: It is *very bad style* to call srand in a function (other than a function which is called once at program initialization). Unless you have an unusual requirement and know what you are doing, `srand` should only be called once, at program startup, and it is a general principle that no library function should have the undocumented side-effect of resetting the random number seed. – rici Jan 04 '15 at 17:25
  • @AshishChugh If you want something threadsafe, this is wrong. – deviantfan Jan 04 '15 at 17:43
  • You should get a [good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) on C++ and _read_ it. – Captain Obvlious Jan 04 '15 at 17:45
  • @deviantfan As rici points out, even without thread safety issues, this is wrong. (With regards to thread safety, the function `rand()` is itself not threadsafe.) – James Kanze Jan 04 '15 at 17:46

4 Answers4

4

It returns a pointer to the first element of an array of int with static storage. The array is valid through the lifetime of the program.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
1
int* getRandom() {}

This defines a function which doesn't take any argument and returns pointer to int. In your case it's returning pointer to first element of array of integers. As that array is statically allocated it will be available even when this function exits.

ravi
  • 10,994
  • 1
  • 18
  • 36
1

The function returns a pointer to int. That's the significance of the asterisk.

The syntax is not dissimilar to how the asterisk is used in the declaration of variables, function arguments etc.

The reason the function can return r where r is an array rather than a pointer is that arrays "decay" into pointers.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Return int Pointer Because ,

At the point where this function returns integer pointer, needs more then just one integer, so in this case pointer return with the address of "0" index. by using this pointer we can access any value given in that array,

Array is static so it creates at start of execution & dispose at termination of program.

Khurram Sharif
  • 504
  • 1
  • 4
  • 20