How to reliably get size of C-style array?

后端 未结 10 1965
广开言路
广开言路 2020-11-29 09:37

How do I reliably get the size of a C-style array? The method often recommended seems to be to use sizeof, but it doesn\'t work in the foo function

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 10:03

    Now, you can use C++11's extent and rank.

    By example:

    #include 
    #include 
    
    int main()
    {
      int a[][3] = {{1, 2, 3}, {4, 5, 6}};
    
      std::cout << "\nRank:           : " << std::rank::value;
      std::cout << "\nSize: [_here_][]: " << std::extent::value;
      std::cout << "\nSize: [][_here_]: " << std::extent::value;
      std::cout << "\nSize: [][]_here_: " << std::extent::value;
    }
    

    prints:

    Rank:           : 2
    Size: [_here_][]: 2
    Size: [][_here_]: 3
    Size: [][]_here_: 0
    

提交回复
热议问题