-4

There is an array :

...
int score[3];
...
score[0] = 6;
score[1] = 4;
score[2] = 7;

How to get the array's number of elements ? ( here it is obvious but I want to ask a question in general )

pheromix
  • 18,213
  • 29
  • 88
  • 158
  • 2
    Please make a minimal research before posting a question, or at least demonstrate some efforts. – Maroun Nov 27 '14 at 14:51
  • 1
    In most cases as soon as you pass the array to a function as an argument the size information is lost. Why you want to use arrays in the first place? C++ arrays is low-level mechanism best suited for libraries. The C++ equivalent of arrays from other languages is `std::vector`. – Wojtek Surowka Nov 27 '14 at 14:52
  • possible duplicate of [How do I find the length of an array?](http://stackoverflow.com/questions/4108313/how-do-i-find-the-length-of-an-array) – macfij Nov 27 '14 at 15:05

3 Answers3

11

Several ways:

  • std::distance(std::begin(score), std::end(score))
  • std::extent<decltype(score)>::value
  • C++17 (N4280): std::size(score)

See also this answer.

Community
  • 1
  • 1
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 1
    great idea to include future functions c++17. this makes this answer still valid in 6 Years – deW1 Nov 27 '14 at 14:53
2

Usually it is a sizeof(score) / sizeof(score[0]). The advantage of this method is understanding of how array works. And it may be the fastest one too, since sizeof works at compile time and whole expression could be optimized by compiler.

d453
  • 519
  • 6
  • 10
1

You can write a macro for that.

#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(*arr))

You should make yourself familiar with containers (like std::vector) which C++ offers. Many of them have methods that can give you actual count of elements stored (size() or length()).

Regarding C-style arrays, in scenarios where they are passed to function as argument, their size is not known, because an array is just a const pointer.

macfij
  • 3,093
  • 1
  • 19
  • 24
  • 2
    That's somewhat dangerous since it will accept a pointer (or any other type with a unary `*` operator), and give surprising results. C++ has safer options. – Mike Seymour Nov 27 '14 at 14:52
  • Agreed, but that was the first thing that came to my mind for C-style arrays. – macfij Nov 27 '14 at 14:57
  • 1
    Even then, a function template is safer. `template size_t size(T(&)[N]) {return N;}` will work for an array, but will give an error rather than a weird result for a pointer. – Mike Seymour Nov 27 '14 at 16:18