Size of array object passed to function

末鹿安然 提交于 2019-11-28 14:20:24

问题


I am running the following code in C++:

class Tile {
    //class definition
};

bool myFunction(Tile* Tiles) {
    sizeof(Tiles);
    sizeof(Tiles[0]);
    //other code
}

int main () {
    Tile tiles [16];
    //other stuff
    myFunction(tiles);
    return 0;
}

When I use the sizeof method as depicted above, it only gives me the size of the pointer, rather than the actual object. I am trying to find the size of the object. My question is how do I take the size of the object given a pointer?


回答1:


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.




回答2:


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()
}



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/32515366/size-of-array-object-passed-to-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!