This is the program.
What I want to do here is to generate 10 random numbers and save it in the array using a function. Then I will display it using a for loop in the driver funtion main(). I don't want to use pointers and vectors. I'm experimenting with actual,formal parameters and passing array.
The problem is line 29.
In trying to fixed that line, i tried the following:
1. remove line 24
error: trial undeclared(first use this function)
2. change it to line 29 cout <<fArray[ctr]=tryArray(fArray[ctr]);
error: invalid conversion from `int' to `int*'
#include<iostream>
#include<time.h>
usingnamespace std;
constint size=10;
int tryArray(int Array[size])
{
int i;
//this will input 10 random numbers to the array
for (i=0; i<size; i++)
{
Array[i]=rand()%10;
}
return Array[i]; //returns the generated 10 random numbers
}
int main()
{
srand(time(NULL));
int fArray[size];
int trial[size];
//output the 10 generated random numbers from the function tryArray()
for( int ctr=0; ctr<size; ctr++)
{
//invalid conversion from int to int*
cout <<fArray[ctr]=tryArray(trial[size]);
}
system("PAUSE");
return 0;
}
int tryArray(int Array[size]) is the same as: int tryArray(int* Array). The size parameter is completely ignored. You may even get a warning to that effect.
On line 29, trial[size] is an (out-of-bounds) element of the array. You want to pass the address of the first element of the array which is normally done by feeding the name of the array to the function: tryArray(trial).
Line 16: return Array[i]; //returns the generated 10 random numbers
This does not return the generated 10 random numbers. It returns one int. Since you didn't actually pass the array, but a pointer to the first element, you don't need to return the values. Unfortunately, i is equal to size at this point in the function, so Array[i] accesses out-of-bounds memory.
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
constint size=10;
void tryArray(int * Array) // or int Array[] or int array[size] if you prefer.
{
for ( int i=0; i<size; ++i )
Array[i] = rand() % 10 ;
}
int main()
{
srand(time(NULL));
int trial[size];
tryArray(trial) ;
//output the 10 generated random numbers from the function tryArray()
for( int ctr=0; ctr<size; ctr++)
cout << trial[ctr] << ' ' ;
system("PAUSE");
return 0;
}
Oh so that's it.
I still followed my own code. But instead of using line 29: cout <<fArray[ctr]=tryArray(trial[size]);
I used your : line 20: tryArray(trial) ;line 23: cout << trial[ctr] << ' ' ;
And it worked.
I think one of the errors I made is incorrectly calling the function. I just realized now what you did. I learned. Thanks.
int tryArray(int Array[size]) is the same as:
int tryArray(int* Array). The size parameter is completely ignored. You may even get a warning to that effect.
^ that I didn't know. Will that only apply to array?