0

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;
	}
}
3
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by mvmalderen
0

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

0

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

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.