Is there a way of printing arrays in C++?
I\'m trying to make a function that reverses a user-input array and then prints it out. I tried Googling this problem and i
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
void print(Type const(& array)[Size]) {
for(int i=0; i
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 const &v) {
std::vector::size_type i;
for(i = 0; i
You can, of course, also make this a template to accept vectors of other types.