There are declared arrays and arrays that are not declared, but otherwise created, particularly using new
:
int *p = new int[3];
That array with 3 elements is created dynamically (and that 3
could have been calculated at runtime, too), and a pointer to it which has the size erased from its type is assigned to p
. You cannot get the size anymore to print that array. A function that only receives the pointer to it can thus not print that array.
Printing declared arrays is easy. You can use sizeof
to get their size and pass that size along to the function including a pointer to that array's elements. But you can also create a template that accepts the array, and deduces its size from its declared type:
template<typename Type, int Size>
void print(Type const(& array)[Size]) {
for(int i=0; i<Size; i++)
std::cout << array[i] << std::endl;
}
The problem with this is that it won't accept pointers (obviously). The easiest solution, I think, is to use std::vector
. It is a dynamic, resizable "array" (with the semantics you would expect from a real one), which has a size
member function:
void print(std::vector<int> const &v) {
std::vector<int>::size_type i;
for(i = 0; i<v.size(); i++)
std::cout << v[i] << std::endl;
}
You can, of course, also make this a template to accept vectors of other types.