home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!cs.utexas.edu!sun-barr!olivea!charnel!sifon!thunder.mcrcim.mcgill.edu!mouse
- From: mouse@thunder.mcrcim.mcgill.edu (der Mouse)
- Newsgroups: comp.lang.c
- Subject: Re: allocating 2-d array
- Message-ID: <1992Dec23.174026.12700@thunder.mcrcim.mcgill.edu>
- Date: 23 Dec 92 17:40:26 GMT
- References: <1992Dec22.185523.4732@nynexst.com>
- Organization: McGill Research Centre for Intelligent Machines
- Lines: 46
-
- In article <1992Dec22.185523.4732@nynexst.com>, jsd@nynexst.com (Joseph Delotto) writes:
-
- > I want to dynamically allocate a 2-d array for a variable defined as:
-
- > int **myarray;
-
- > where the dimensions = nrows,ncols. Currently I'm using the
- > following code:
-
- > myarray = (int **) malloc ((unsigned) nrows*sizeof(int*));
- > for(i=0;i<=nrows;i++)
- > myarray[i] = (int *) malloc ((unsigned) ncols*sizeof(int));
-
- > which seems to work ok but looks awfully sloppy. Is there any way to
- > get the whole thing done in one shot?
-
- No, not unless it's "char **myarray", because only chars are known to
- have no alignment restrictions. But you can do it with only two
- mallocs:
-
- myarray = (int **) malloc(nrows*sizeof(int *));
- myarray[0] = (int *) malloc(nrows*ncols*sizeof(int));
- for (i=1;i<nrows;i++) myarray[i] = myarray[i-1] + ncols;
-
- (Note that your initial code ran 0..nrows, not 0..nrows-1. Thus, you
- were writing into more memory than your first malloc allocated.)
-
- If it *is* chars, you can do
-
- { char *tmp;
- tmp = malloc((nrows*sizeof(char *))+(nrows*ncols));
- myarray = (char **) tmp;
- tmp += nrows * sizeof(char *);
- for (i=0;i<nrows;i++) { myarray[i] = tmp; tmp += ncols; }
- }
-
- but this depends on the alignment of char * being acceptable for char.
- For no other type is the analogous restriction known a priori to be
- satisfied, which is why this can be done only for chars. (Unless, of
- course, it's in machine-specific code where you don't mind depending on
- the alignment behavior of your particular machine.)
-
- der Mouse
-
- mouse@larry.mcrcim.mcgill.edu
-