How to pass 2D variable-sized arrays in C++?

Jason Mancini
Mon Sep 30 14:48:00 GMT 2002

Hi again,
After many tries, I propose that this is the "correct solution".
The compiler should hide the address calculation for me -- this
is why we have compilers after all!
Jason Mancini

void func(int c, int r, float *fa)
  float (*f)[c] = (float (*)[c])fa;
  ... f[xr][xc] ...

  int c = 5, r = 4;
  float f[r][c];
  func(c, r, &f[0][0]);


Claudio Bley wrote:

The second problem is that it might not do what you expect when you
want to use it in the usual notation f[i][j] which is actually
equivalent to (*(*(f+i)+j)).

The correct solution is to use it like so:

void print_mn (int m, int n, float *f)
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
cout << f[i*n+j] << '\t';
cout << endl;

float[4][5] f;
print_mn (4, 5, &f[0][0]);

Send and receive Hotmail on your mobile device:

More information about the Gcc-help mailing list