function argument

Hello...

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;

void show(int matriz[n][n]){ //
int c,f;
for(f=0;f<=n-1;f++){
for(c=0;c<=n-1;c++){
cout<< matriz[f][c]<<"\t";
};
cout<<"\n";
};
}

main (){

int n;
cout<<"Print a nxn matrix.";
cin>>n;
int matrix[n][n];
show(matrix);
system("pause");
}
1. Code tags, please.

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.

I use C++ in Code::Blocks.

Ok, I'll try to slowly understand the answer cause I'm kind of a beginner in programing.
Thanks for the data.
Topic archived. No new replies allowed.