-
array problem
this program uses read() function to input values and print out arrays with print() function
however, i cannot get the arrays printed correctly...
Code:
void read(int[], int);
void print(int[], int);
int main()
{ const int MAXSIZE=100;
int a[MAXSIZE]={0}, size;
read(a,size);
cout<<"The array has "<<size<<" elements: ";
print(a,size);
}
void read(int a[], int n)
{cout<< "Enter integers. Terminate with 0: \n";
n=0;
const int MAXSIZE=100;
do
{cout<< "a["<< n << "] : ";
cin>>a[n];
}while (a[n++] != 0 && n<MAXSIZE);
--n;
}
void print(int a[], int n)
{for (int i=0; i<n; i++)
cout<< a[i]<< " ";
}
it always comes out as 0 array and no values being inserted.
Thanks for the help.
-
The 2nd parameter of read() needs to be a reference parameter, for changes in read() to be visible to the size variable declared in main()
-
can some one explain why reference parameter is needed in this program?
thnx
-
Unless you say otherwise, size (in your code) will be passed by value.
This means your function gets a copy of size, not size itself.
Your function then modifies this copy (not the original), so by the time you get back to main, size is left as it was (uninitialised).
You could also write the code like this
size = read ( a );
Where read is coded to return an int, and you finish the function with
return n;
-
Note that the reason your "a" parameter seems to be modified without passing it by reference is that it is a pointer variable. This means that the function is making a copy of the pointer contents you pass for "a" and, since the contents of said copy happen to be the address of in memory at which the array data begins, you are, in fact, able to modify the array data without modifying the pointer variable.