I am running the following code in C++:
class Tile {
//class definition
};
bool myFunction(Tile* Tiles) {
sizeof(Tiles);
sizeof(Tiles[0]);
/
The simplest, C-sytle way is to pass the array size as a parameter.
bool myFunction_ver1(Tile* Tiles, std::size_t size)
{
//...
}
But C++ offers more. Since array size is contained in the data type of the array, a template can help. The array should be passed by reference to prevent the array from being adjusted to pointer.
template <std::size_t N>
bool myFunction_ver2(const Tile (&Tiles)[N])
{
// N is the array size
}
But we should prefer using std::array
or std::vector
instead of raw array.
template <std::size_t N>
bool myFunction_ver3(const std::array<Tile, N>& Tiles)
{
// You may use N or Tiles.size()
}
bool myFunction_ver4(const std::vector<Tile>& Tiles)
{
// use Tiles.size()
}
Arrays naturally decays to pointers, and when they do that all size information is lost. The most common solution is to pass along the number of elements in the array as an argument. It's also possible to use templates to deduce the array size.
Or use std::array (or std::vector, depending on situation) instead, which is the solution I recommend.
Answering my own question:
Why I'm posting this answer
I was new to C++ at the time, and other questions have been marked as a duplicate of this. As such, I'm guessing that other questions like this are from C++ newbies. This answer will be for the benefit of those newbies.
My answer
Unlike in higher-level languages like Python or JAVA, the length of an array is not stored with the contents of the array, so there is no way to access it.
As such, it must be passed as a separate parameter. It may not make much sense in higher-level languages, but it's necessary in both C and C++.
Also, unlike in Python and JAVA, an array is not an object. To fully understand C/C++ arrays, one first must understand pointers.
Raw arrays decay to pointers as function arguments, so any length information associated with the type is erased without using templates. So, using raw arrays you can pass the size of the array as an argument.
bool myFunction(std::size_t n, Tile tiles[n]) {
std::size_t z = n * sizeof(Tile);
// etc...
}
Using either std::vector
or std::array
is generally a better solution though.