I'm trying to write a function that takes an array of any length as an argument and prints out each element in a new line, but since sizeof()
returns its size in bytes, I tried dividing the size of the array by the size of a single element. When I tried running the programme passing an array with 9 elements, it only printed out the first two.
The function:
void PrintArray(int anArray[])
{
using namespace std;
int nElements = sizeof(anArray) / sizeof(anArray[0]);
for (int nIndex=0; nIndex < nElements; nIndex++)
cout << anArray[nIndex] << endl;
}
In order to find out what was wrong, I commented out the loop and added the statement
cout << sizeof(anArray) << " " << sizeof(anArray[0]) << endl;
and it printed out 8 4
. How is it even possible for a 9 element array to be 8 bytes long? Does something happen to it when it's passed as an argument?
(Also, I have no clue how vectors work. I got started with C++ 3 days ago).