How do I use Malloc to dynamically create a two dimensional array

Mark Gelinas gelinasm at merrimack.edu
Sun Jan 20 00:05:55 AEST 1991


In article <7046 at crash.cts.com>, kevin at crash.cts.com (Kevin Hill) writes:
>    I have a problem, and it may seem basic, but how do I use
> malloc to create an array of type int i[100][100];
>

	Since 2-D arrays can exist as consecutive addresses in memory,
(stored/read rowwise I believe), why not try something like

	int **i;
	int rowsize, colsize;
	.
	.
	*i = (int *) malloc(sizeof(int)*rowsize*colsize);

For example, a 100 x 100 array would be

	int **i;
	int rowsize=100, colsize=100;
	.
	.
	*i = (int *) malloc(sizeof(int)*rowsize*colsize);

I have not tried this myself, but from what I can recall, it should work.

Corrections, questions, additional suggestions welcomed.

Mark

P.S.  Anyone know of any graduate schools with chemistry programs
      geared toward computer applications (data modelling, computer
      to instrument interfaces, simulations, etc)?  If so, please
      mail me direct.  Thanks.

-- 
- - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Mark Gelinas      | UUCP:    samsung!hubdub!GELINASM
Merrimack College | or       GELINASM at merrimack.edu



More information about the Comp.lang.c mailing list