C++ equivalent of Java's length

Java
1
2
3
4
  int numbers[] = new int[5];
  for(int i = 0; i < numbers.length; i++) {
    //do stuff
  }

C++
1
2
3
4
5
6
  int *numbers;
  numbers = new int[5];
  for(int i = 0; i < numbers ??? ; i++) 
  {
    //do stuff
  }


How would I replicate that code in C++?
Last edited on
Be sure there is no direct equivalent, though you can use macro like:

#define DIM(a) (sizeof(a)/(sizeof(*a)))

C (and C++) does not care about any properties of array except its address, so you can easily miss the end of array and spoil some other variable's memory.

Or better use STL containers, like "list" etc. instead of simple arrays. They are like collections in java...
Last edited on
Okay :(
1
2
3
4
5
6
7
8
9
10
11
#include <vector>

int main()
{
    std::vector<int> numbers(5) ;

    for( std::size_t i = 0 ; i < numbers.size() ; ++i )
    {
        // do stuff
    }
}

See: http://www.mochima.com/tutorials/vectors.html
Topic archived. No new replies allowed.