This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

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


>>>>> "Quang" == Quang Nguyen (Ngo) <quang.nguyen@tapeware.com> writes:

    Quang> Hi Jason, Try this:

    Quang> void func(int c, int r, float f[][]) { printf("hello\n"); }

    Quang> main() { int c = 5, r = 7; float f[r][c];

    Quang>         func(c, r, f); }

Note, that this is no valid C++ code. You may just leave out the first
dimension of an multidimensional array ( e.g. f[5][] or f[5][4][8][] )
because the compiler needs this information in order to find the
position of an element.

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]);


To the OP: Please post this sort of language specific (non GCC
specific) questions in the appropriate forum next time. And may I
suggest that you get a good book on C++ programming?

-- 
Claudio Bley                                 ASCII ribbon campaign (")
Debian GNU/Linux advocate                     - against HTML email  X 
http://www.cs.uni-magdeburg.de/~bley/                     & vCards / \


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]