How to compute size of an array parameter in a function?
Consider below C++ program:
The above output is for a machine where size of integer is 4 bytes and size of a pointer is 8 bytes.
The cout statement inside main prints 40, and cout in findSize prints 8. The reason is, arrays are always passed pointers in functions, i.e., findSize(int arr) and findSize(int *arr) mean exactly same thing. Therefore the cout statement inside findSize() prints size of a pointer. See this and this for details.
How to find size of array in function?
We can pass a ‘reference to the array’.
The above program doesn’t look good as we have hardcoded size of array parameter. We can do it better using templates in C++.
We can make a generic function as well:
40 40 80 80
Now the next step is to print the size of a dynamically allocated array. It’s your task man ! I’m giving you a hint.
This article is contributed Swarupananda Dhua Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- How to pass a 2D array as a parameter in C?
- Parameter Passing Techniques in C/C++
- Difference between Argument and Parameter in C/C++ with Examples
- array::size() in C++ STL
- How to find size of array in C/C++ without using sizeof ?
- C++ Program to print an Array using Recursion
- How to print dimensions of multidimensional array in C++
- size of char datatype and char array in C
- Get the stack size and set the stack size of thread attribute in C
- set::size() in C++ STL
- map::size() in C++ STL
- match_results size() in C++ STL
- bitset size() in C++ STL
- unordered_map size() in C++ STL
- unordered_multiset size() in C++ STL