0

why is 1

hello, I want to get number of elements of a array, but I encounter a doubt about the following codes: /* correct array size */ #include <iostream> using namespace std; int main() { int numbers[100]; cout << sizeof(numbers) / sizeof(int); return 0; } /* uncorrect array size */ #include <iostream> using namespace std; // Define a function to get size of an array. int getSize(int arr[]) { return sizeof(arr)/sizeof(arr[0]); } int main() { int numbers[100]; cout << getSize(numbers); // the result is 1, why ? return 0; } So, why I get the result is '1' from 2nd program, Thank you !

9th Aug 2017, 3:09 AM
zhouyl
zhouyl - avatar
4 odpowiedzi
+ 10
Arrays decay to pointers when passed as function parameters so sizeof is not going to help you. Refer: https://stackoverflow.com/questions/968001/determine-size-of-array-if-passed-to-function
9th Aug 2017, 3:28 AM
Hatsy Rei
Hatsy Rei - avatar
+ 6
in simple word, when you pass an array to a function you send the first element of array to that function (as a pointer), so you get the size of the first element obviously
9th Aug 2017, 3:36 AM
Babak
Babak - avatar
+ 2
You can use a template/generic. #include <iostream> using namespace std; #include <iostream> using namespace std; template <typename T, int N> int getSize(T (&arr) [N]) { // You could just return N instead here though // Or get rid of N completely using: // template <typename T> // int getSize(T &arr) return sizeof(arr)/sizeof(arr[0]); } int main() { int numbers[100]; cout << getSize(numbers); return 0; }
9th Aug 2017, 4:21 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
This is one of the reasons why you should use std::array, it keeps track of its own size without having to keep track of it yourself
9th Aug 2017, 7:26 AM
aklex
aklex - avatar