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++?
C++ – How to get the size of an Array?
arraysc
Related Topic
- Javascript – How to empty an array in JavaScript
- C++ – the “–>” operator in C/C++
- Javascript – Loop through an array in JavaScript
- Javascript – How to check if an object is an array?
- Javascript – How to remove a specific item from an array
- Javascript – Copy array by value
- Javascript – For-each over an array in JavaScript
- Java – Why is processing a sorted array faster than processing an unsorted array
Best Answer
It really depends what you mean by "array". Arrays in C++ will have a size (meaning the "raw" byte-size now) that equals to N times the size of one item. By that one can easily get the number of items using the
sizeof
operator. But this requires that you still have access to the type of that array. Once you pass it to functions, it will be converted to pointers, and then you are lost. No size can be determined anymore. You will have to construct some other way that relies on the value of the elements to calculate the size.Here are some examples:
If we now lose the name "a" (and therefor its type), for example by passing "pa" to a function where that function only then has the value of that pointer, then we are out of luck. We then cannot receive the size anymore. We would need to pass the size along with the pointer to that function.
The same restrictions apply when we get an array by using
new
. It returns a pointer pointing to that array's elements, and thus the size will be lost.It can't return a pointer that has the type of the array incorporated, because the size of the array created with
new
can be calculated at runtime. But types in C++ must be set at compile-time. Thus,new
erases that array part, and returns a pointer to the elements instead. Note that you don't need to mess withnew
in C++. You can use thestd::vector
template, as recommended by another answer.