I want to declare a function that prints any nxn matrix
But the compiler won't let me declare a function for a variable dimension. How can I declare that function. I did this:
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
2. VLA, variable-length arrays, are not in the C++ standard. The size of the "matrix" should be known at compile-time so that compiler can create instructions that statically allocate that fixed size block of memory from stack along with other variables of function main().
3. Same limitation in the function parameter. You could have void show( int matriz[][N] )
The N has to be known, because when you write matriz[f]
the code actually computes (&matriz[0][0]) + f*N
The latter you can do yourself:
1 2 3 4 5 6 7 8 9
void show( int * matriz, int n ) {
// the matriz is assumed to contain n*n elements as "square matrix"
for ( int f=0; f < n; ++f ) {
for ( int c=0; c < n; ++c ) {
cout << matriz[ f*n + c ] << '\t';
}
cout << '\n';
}
}
The main() in turn should dynamically allocate a block of n*n elements and pass its address to the function.