Questions About Array Declaration

Dear all,

Some time I see such a code:

1
2
   int array[] = { -2, 99, 0, -743, 2, 3, 4 };
   int array_size = 7;


Why [] and size is separated and why the array is not declared this way?

 
   int array[7] = { -2, 99, 0, -743, 2, 3, 4 };


Is there any case where only Array is preferrable than
vector.
when you have [] on array declaration means that the array size is chosen by the compiler depending on the elements given.
An array is useful just for simple stuff
Last edited on
Well, the above code is stupid. The size is omitted usually so that the programmer doesn't have to count the elements, since the compiler is pretty good at counting.

But line 2 should read

 
int array_size = sizeof(array) / sizeof( array[0] );


Or better yet

1
2
3
4
5
6
template< typename T, size_t N >
size_t ArraySize( T (&)[ N ] )
{ return N; }

//...
int array_size = ArraySize( array );

Topic archived. No new replies allowed.