+ 1
sizeof return different values when it is called inside a function
In this code the sizeof function returns two different value when is called inside main and when it is called inside printArray. In main returns 12 which is what expected. In printArray returns 4. can anyone explain why? #include <iostream> using namespace std; void printArray(int arr[], int size) { cout << "sizeof inside printArray: " << sizeof(arr) << endl; for(int x=0; x<size; x++) { cout <<arr[x]<< endl; } } int main() { int myArr[3]= {42, 33, 88}; cout << "sizeof inside main: " << sizeof(myArr) << endl; printArray(myArr, 3); }
3 Respostas
+ 3
The main function returns the sizeof the whole array (3 integers * 4 bytes = 12) and the prinArray function receives a pointer to the first element of the array and returns the sizeof the pointer (4 bytes). To test this, add another integer in your array. The main function sizeof will be 16 and the printArray sizeof will still be 4.
0
Try different compiler.. Use some compiler online
0
Thanks Andrei. That make sense now. I did another test to make sure the pointer to the array is passed on not the whole array. I changed the value of one of the elements of the array inside printArray and that value was updated in the main as well.
#include <iostream>
using namespace std;
void printArray(int arr[], int size) {
cout << "sizeof inside printArray: " << sizeof(arr) << endl;
for(int x=0; x<size; x++) {
cout <<arr[x]<< endl;
}
arr[2] = 200; // change the last element
}
int main() {
int myArr[3]= {42, 33, 88};
cout << "sizeof inside main: " << sizeof(myArr) << endl;
printArray(myArr, 3);
cout << myArr[2]; // prints 200
}