Hello All,

I am trying to generate an array which has random integers and pass this array to a function to be able to print random integers. The code I have written is as below. Can you help me about that?
Thanks

#include <iostream>
#include <ctime>
using namespace std;
void generate_array(int& f_array[]);
void print_array(int& p_array[]);
int main()
{	
	int num_arry[4];
	generate_array(num_arry);
	print_array(num_arry);

	/*srand((unsigned)time(0)); 
    int random_integer; 
	for(int index=0; index<5; index++){ 
        random_integer = (rand()%1000)+1; 
        cout << random_integer << endl; 
    } 
	*/
}

void generate_array(int& f_array[])
{
	srand((unsigned)time(0));
	for (int index = 0; index<5; index++)
	{
		f_array[index]=(rand()%1000)+1;
	}
}
void print_array(int& p_array[])
{
	for(int i = 0; i<5; i++)
	{
		cout << "numbers" << p_array[i] << endl;
	}
}

Recommended Answers

All 3 Replies

Remove the & pass by reference symbols from the functions

void generate_array(int& f_array[]);
void print_array(int& p_array[]);

Let the functions just be:

void generate_array(int f_array[]);
void print_array(int p_array[]);

It works fine...

Dear csurfer, I appreciate for your help,it works now. By the way, how can I do it with "call by reference" method? Some friends claim that "call by reference" is better. Do you have any suggestion about "call by reference" ? What is the advantage of "call by reference" ?
Thanks

Dear csurfer, I appreciate for your help,it works now. By the way, how can I do it with "call by reference" method? Some friends claim that "call by reference" is better. Do you have any suggestion about "call by reference" ? What is the advantage of "call by reference" ?
Thanks

With 'better' they probably mean that the data is quicker available to the function when passed by reference, this is because not all the data is copied into the function parameter, but instead of that just a reference to that data is given as an argument to that function, which means that your program doesn't lose time to copy the whole variable's contents.

In this case there's no real performance difference because the array name is converted to a constant pointer to the first element of itself, when you pass it to the function.
(The array's contents aren't copied, just a constant pointer to the first element of the array is passed as an argument).

Resume:
pass by value: the whole variable is copied.
pass by reference: the variable is not copied, instead a reference to that variable is passed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.