0

For example, I have an array with 3 elements

int array [] = {1, 4, 66};

How can I know how many elements array contains?

normanius
  • 8,629
  • 7
  • 53
  • 83

2 Answers2

5

Do this with:

std::size(myarray);

std::size is in <iterator>.


Some sources will tell you to use a "trick" like sizeof(myarray)/sizeof(myarray[0]). But this is error-prone. The name of an array decays really easily to a pointer, for which this "trick" gives the wrong result. std::size will either work, or break the build.

Plus, when you switch from C arrays to std::array, it'll still work!

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

You can use sizeof(myarray)/sizeof(int).

But you really should start using std::array, which does the same thing as your array and is safer. And comes with a size() method.

Paul92
  • 8,827
  • 1
  • 23
  • 37