Reputation: 287
I want to write a function in C++ that take a matrix of any size and print it.
my code is as follows and it works. But my questions:
1) Is it the best practice?
2) Why casting using (int *)
works but static_cast<int *>
does not?
Thanks
#include <iostream>
using namespace std;
void print_matrix(int *, int, int);
int main()
{
int mat[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int mat2[5][5] = {{1, 2, 3, 40, 50},
{4, 5, 6, 70, 80},
{7, 8, 9, 10, 20},
{17, 18, 19, 10, 20},
{71, 81, 91, 110, 120}
};
print_matrix((int *)mat2, 5, 5);
cout << endl;
print_matrix((int *)(mat), 3, 3);
cout << endl;
// static cast does not work:
// error: invalid static_cast from type 'int [3][3]' to type 'int*'|
// print_matrix(static_cast<int *>(mat), 3, 3);
return 0;
}
void print_matrix(int *matPtr, int row, int col)
{
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++)
cout << *(matPtr + col * i + j) << '\t';
cout << endl;
}
}
Upvotes: 0
Views: 99
Reputation: 206717
Is it the best practice?
No, it is not.
It will be better to use a function template.
template <size_t NR, size_t NC>
void print_matrix(int (&matrix)[NR][NC])
{
...
}
and call it as:
print_matrix(mat2); // NR and NC are deduced by the compiler
Why casting using
(int *)
works butstatic_cast<int *>
does not?
Given
int mat[3][3] = { ... };
the following pointers have the same numerical value even though the pointers are of different types.
int (*p1)[3][3] = &mat;
int (*p2)[3] = &mat[0];
int *p3 = &mat[0][0];
Because of this coincidence, use of (int*)
works.
Using static_cast<int*>
does not work because when a 2D array decays to a pointer, it does not decay to int*
-- mat
decays to int (*)[3]
(pointer to an "array of 3 int
s") and mat2
decays to int (*)[5]
(pointer to an "array of 5 int
s"). They cannot be cast to int*
in general.
Upvotes: 1