Wednesday, 3 May 2017

c++ - How to get the size of an Array?




In C# I use the Length property embedded to the array I'd like to get the size of.
How to do that in C++?


Answer



Arrays in C/C++ do not store their lengths in memory, so it is impossible to find their size purely given a pointer to an array. Any code using arrays in those languages relies on a constant known size, or a separate variable being passed around that specifies their size.




A common solution to this, if it does present a problem, is to use the std::vector class from the standard library, which is much closer to a managed (C#) array, i.e. stores its length and additionally has a few useful member functions (for searching and manipulation).



Using std::vector, you can simply call vector.size() to get its size/length.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...