Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site psivax.UUCP Path: utzoo!watmath!clyde!burl!ulysses!mhuxr!mhuxt!houxm!whuxl!whuxlm!akgua!sdcsvax!sdcrdcf!psivax!friesen From: friesen@psivax.UUCP (Stanley Friesen) Newsgroups: net.lang.c Subject: Re: help converting multi-dim arrays Message-ID: <386@psivax.UUCP> Date: Tue, 9-Apr-85 12:55:53 EST Article-I.D.: psivax.386 Posted: Tue Apr 9 12:55:53 1985 Date-Received: Sat, 13-Apr-85 04:22:32 EST References: <569@utcs.UUCP> Reply-To: friesen@psivax.UUCP (Stanley friesen) Organization: Pacesetter Systems Inc., Sylmar, CA Lines: 57 Summary: In article <569@utcs.UUCP> physics@utcs.UUCP writes: >From utfyzx!harrison Thu Apr 4 19:53:50 1985 >Received: by utcs.UUCP (4.24/4.7) id AA12979; Thu, 4 Apr 85 19:53:46 est >Date: Thu, 4 Apr 85 19:53:46 est >From: utfyzx!harrison >Apparently-To: physics >[] >The problem: a large piece of code with a number of arrays, some >2 dimensional and a few 3 dimensional, accessed with lines like: > > for(row=0; row for(col=0; col ...data[row][col] ... > >The declaration of the matrices, such as > > static double data[MAXROWS][MAXCOLS]; /* just like FORTRAN */ > >is larger than any conceivable set of data it will be asked to >deal with, and wastes scads of memory. So, we want to convert >the code to use malloc(3C) to dynamically allocate memory and >save all that wasted space. But, we still want to access the >matrices as: > ...data[row][col] ... >Any ideas? >Dave Harrison, Dept. of Physics, Univ. of Toronto: ..utzoo!utcs!physics Fairly simple. given that you can can calculate the number of rows and columns desired the following should work: char *calloc(); double **vec; int rows, cols, i; rows = some stuff; cols = other stuff; /* Allocate a vector of row pointers of size rows */ vec = (double **)calloc(rows, sizeof(double *)); /* Allocate a vector of doubles for each row */ for(i = 0; i < rows; i++) { vec[i] = (double *)calloc(cols, sizeof(double)); } And make sure all your routines that use it know how many rows and columns actually exist and never access past the end. With this proviso "vec" is usable *exactly* like "data" above. If you do not have calloc() it is equivalent to malloc(num*size) -- Sarima (Stanley Friesen) {trwrb|allegra|cbosgd|hplabs|ihnp4|aero!uscvax!akgua}!sdcrdcf!psivax!friesen or {ttdica|quad1|bellcore|scgvaxd}!psivax!friesen