How can I get array size in function call? 010000110010101100101011

When I pass a array in function, taking the size of the array seems to give the size of the array pointer: https://code.sololearn.com/cbdfREro7Y7h/#cpp I know I could just pass take the size from outside the function call and pass it as an argument, but I would want to know if there is a way to get the size of the array inside the function call, using the sizeof operator: void printArrayLength(bool arr[]) { cout << sizeof ??? << endl; }

3/1/2020 12:50:05 PM

Seb TheS

5 Answers

New Answer


Seb TheS The rationale for not allowing it is that in those days memory was very expensive. To be able to calculate the size, one needs full access to array, which means copying the array content to the function stack. Instead it was decided to pass a pointer and ensure that arrays are laid in a contiguous memory space. Then one can iterate over it using pointers If you really want to calculate the array size in the function them pass a pointer to the array. void fun( bool (*arr)[2]) { cout << sizeof(*arr); } // function call fun(&arr); Another way if bool arr[] = {true, false} then array size is (&arr + 1);


bool arr[] = {false, false}; int sz = sizeof(arr)/sizeof(bool); will give you the sizeof(array) number of elements. Your code does not work because arrays when passed to function decay to pointers and loose size information and what you get is the sizeof the pointer. The above will only work if your array is statically allocated by the compiler.


Interesting question. I found some stuff on SO: https://stackoverflow.com/questions/968001/determine-size-of-array-if-passed-to-function It seems it is not possible to determine the size of array from inside a function, if you pass it as a pointer. Some workarounds they suggested : - use a vector instead - if the array size is constant, store the size in a constant too - if the size is known at compile time, you can define a template function and pass the array as reference - pass the size along in a separate argument - use a sentinel value to mark the end (not too practical with bool...)


Tibor Santa ~ swim ~ Return thanks for your arguments; weird the arg array size can't be calculated inside the function call, but let's just calculate the size outside the function call.