I made a class called Box, which has a size of 100 . Then I made an array of 6 "Boxes" , now, the size if 600. However, when I pass this array into a function, and tries to use sizeof in the function, the size of the whole array becomes 4, how come?
I made a class called Box, which has a size of 100 . Then I made an array of 6 "Boxes" , now, the size if 600. However, when I pass this array into a function, and tries to use sizeof in the function, the size of the whole array becomes 4, how come?
An Unofficial Cristiano Ronaldo Website : Ronaldo 7
Because C++ passes an array as a pointer to the first element. When you use sizeof, you're getting the size of a pointer, not an array. One solution is to pass the size as well:
Or encapsulate the array ina class or structure and pass a reference to that:Code:void f ( Box array[], size_t size );
Or even pass a reference to the array. But then you have size limitations that you must adhere to:Code:struct BoxArray { Box array[SIZE]; size_t size; }; void f ( BoxArray& ba );
Code:void f ( Box (&array)[10] );
Last edited by Prelude; 03-07-2004 at 07:19 PM.
My best code is written with the delete key.
ahh, okay, thx.Originally posted by Prelude
Because C++ passes an array as a pointer to the first element. When you use sizeof, you're getting the size of a pointer, not an array. One solution is to pass the size as well:
Or encapsulate the array ina class or structure and pass a reference to that:Code:void f ( Box array[], size_t size );
Or any of a number of other ways. But passing the size along with the array is the simplest.Code:struct BoxArray { Box array[SIZE]; size_t size; }; void f ( BoxArray& ba );
An Unofficial Cristiano Ronaldo Website : Ronaldo 7