Path: utzoo!utgpu!water!watmath!clyde!rutgers!cmcl2!brl-adm!brl-smoke!gwyn From: gwyn@brl-smoke.ARPA (Doug Gwyn ) Newsgroups: comp.lang.c Subject: Re: Allocating a two-dimensional array Message-ID: <7122@brl-smoke.ARPA> Date: 18 Jan 88 01:51:08 GMT References: <1050@ogg.cgrg.ohio-state.edu> Reply-To: gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) Organization: Ballistic Research Lab (BRL), APG, MD. Lines: 30 In article <1050@ogg.cgrg.ohio-state.edu> spencer@ogg.cgrg.ohio-state.edu (PROCEED) writes: >But I can't figure out how to dynamically allocate a two-dimensional >array of floats. (I have to have an N by N matrix of floats, but don't >know N beforehand.) Can anyone help me on this one? Thanks. There are two parts to this. The actual memory allocation is the easy part. The hard part is deciding how your code is to access a matrix element. Since C does not support multi-dimensional arrays that don't have a compile-time constant for every dimension except the first, you cannot directly use C array subscript notation to access the data in a single "rectangular" allocated matrix. There are two solutions, one of them to allocate a one-dimensional array and perform the indexing arithmetic explicitly, using the matrix width, and the other solution is to allocate an extra array of "row vector pointers" then use double indexing. The first method is simpler but usually slower (because index arithmetic is slower than indirection). /* METHOD 1: */ float *matrix = (float *)malloc( M * N * sizeof(float) ); #define Matrix(i,j) matrix[(i)*N + (j)]; /* for convenience */ /* ... */ matrix_ij = Matrix(i,j); /* METHOD 2: */ float *data = (float *)malloc( M * N * sizeof(float) ); float **matrix = (float **)malloc( M * sizeof(float *) ); for ( i = 0; i < M; ++i ) matrix[i] = &data[i*N]; /* ... */ matrix_ij = matrix[i][j];