When an array is passed as a parameter to a function, it is treated identically to a pointer; this is referred to as
array decaying. So your program is equivalent to this one:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
using namespace std;
void getSizeOfArray(int* newArray); // creating a prototype
int main(){
int myArray[3];
//cout << sizeof(myArray) << endl;
getSizeOfArray(myArray);
}
void getSizeOfArray(int* newArray){
cout << sizeof(newArray);
}
|
Where a value of 4 does make sense!?
And this holds for multi-dimensional arrays, too
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
using namespace std;
size_t getSizeOfArray(int newArray[3][4][5]); // creating a prototype
int main(){
int myArray[2][4][5];
cout << "sizeof = " << sizeof(myArray) << endl;
cout << "getSizeOfArray = " << getSizeOfArray(myArray) << endl;
}
size_t getSizeOfArray(int newArray[3][4][5]){
return sizeof(newArray);
}
|
which outputs:
sizeof = 160
getSizeOfArray = 4 |
Also note that I passed a
2 x 4 x 5 array to the function even though it was declared to take a
int newArray[3][4][5]
parameter; the size in the first [] is ignored.
But you can also pass an array by reference, like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
using namespace std;
size_t getSizeOfArray(int (&newArray)[3][4][5]); // creating a prototype
int main(){
int myArray[3][4][5];
cout << "sizeof = " << sizeof(myArray) << endl;
cout << "getSizeOfArray = " << getSizeOfArray(myArray) << endl;
}
size_t getSizeOfArray(int (&newArray)[3][4][5]){
return sizeof(newArray);
}
|
This not only gives the correct array size, it also prevents you from passing an array other than (here) a 3 x 4 x 5 array (otherwise there is a compile error.)
sizeof = 240
getSizeOfArray = 240 |
Andy