I won't repeat my complete answer on why dynamic two-dimensional matrices (and this clearly is one) aren't the way to go in C++.
Answer on: 1D or 2D array, what's faster? (Start reading @ The long answer, or why dynamic 2 dimensional data storage (pointer-to-pointer or vector-of-vector) is "bad" for simple / small matrices.)
You'll find:
- A rather detailed explanation why you don't want to use pointer-to-pointer dynamic arrays
- An example class for simple matrix objects
You won't even need a function that initializes your data to zero.
Just write
matrices::simple<int> matrix_object(6, 6);
to get a zero-initialized matrix of size 6x6.
Now you can access the elements via
matrix_object(0,1) = 2; // sets 2nd element of first row to 2
The "C++ way" of writing the matrix to a stream would involve defining operator<<
for that class like:
template<typename T>
std::ostream & operator<< (std::ostream &stream, matrices::simple<T> const & matrix)
{
typedef typename matrices::simple<T>::size_type size_type;
for (size_type i(0u); i<matrix.rows(); ++i)
{
for (size_type j(0u); j<matrix.cols(); ++j)
stream << std::setw(4) << std::right << matrix(i,j);
stream << std::endl;
}
return stream;
}
You could easily output your matrix this way by writing:
std::cout << matrix_object << std::endl;
Together with the previous snipptes this will output:
0 2 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
If you want to keep going for pointers you'll have to address several issues in your code.
I've added two parameters to enable other sizes but the can be replaced by 6 again if desired.
int** new_initialized_array (size_t const rows, size_t const cols)
{
typedef int* rollarray;
rollarray *m = new rollarray[rows];
size_t allocated_arrays(0u);
try
{
for (size_t i(0u); i < rows; ++i)
{
m[i] = new int[cols];
++allocated_arrays;
for (size_t j(0u); j<cols; ++j) m[i][j] = 0;
}
}
catch (std::bad_alloc & e)
{
for (size_t i(0u); i < allocated_arrays; ++i) delete[] m[i];
delete[] m;
throw;
}
return m;
}
The issues I addressed:
- To return a pointer, the function must have a return type that actually is a pointer (long is an unsigned value).
- You need to track you allocations. If one of them fails you'll need to roll-back the rest to avoid memory leaks.
- You don't need the double-while loop. You have your outer loop already present (the one you do you allocation in) so you only need an inner loop to set the initial values for your array.
- Last but not least I renamed the function. It doesn't actually "initialize" an existing array but creates a new, initialized one.
I can only recommend to read the link above (or any other resource about how to handle 2D-data according to RAII).