home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / lang / c / 18833 < prev    next >
Encoding:
Internet Message Format  |  1992-12-23  |  2.0 KB

  1. Path: sparky!uunet!cs.utexas.edu!sun-barr!olivea!charnel!sifon!thunder.mcrcim.mcgill.edu!mouse
  2. From: mouse@thunder.mcrcim.mcgill.edu (der Mouse)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: allocating 2-d array
  5. Message-ID: <1992Dec23.174026.12700@thunder.mcrcim.mcgill.edu>
  6. Date: 23 Dec 92 17:40:26 GMT
  7. References: <1992Dec22.185523.4732@nynexst.com>
  8. Organization: McGill Research Centre for Intelligent Machines
  9. Lines: 46
  10.  
  11. In article <1992Dec22.185523.4732@nynexst.com>, jsd@nynexst.com (Joseph Delotto) writes:
  12.  
  13. > I want to dynamically allocate a 2-d array for a variable defined as:
  14.  
  15. > int    **myarray;
  16.  
  17. > where the dimensions = nrows,ncols.  Currently I'm using the
  18. > following code:
  19.  
  20. > myarray = (int **) malloc ((unsigned) nrows*sizeof(int*));
  21. > for(i=0;i<=nrows;i++)
  22. >      myarray[i] = (int *) malloc ((unsigned) ncols*sizeof(int));
  23.  
  24. > which seems to work ok but looks awfully sloppy.  Is there any way to
  25. > get the whole thing done in one shot?
  26.  
  27. No, not unless it's "char **myarray", because only chars are known to
  28. have no alignment restrictions.  But you can do it with only two
  29. mallocs:
  30.  
  31. myarray = (int **) malloc(nrows*sizeof(int *));
  32. myarray[0] = (int *) malloc(nrows*ncols*sizeof(int));
  33. for (i=1;i<nrows;i++) myarray[i] = myarray[i-1] + ncols;
  34.  
  35. (Note that your initial code ran 0..nrows, not 0..nrows-1.  Thus, you
  36. were writing into more memory than your first malloc allocated.)
  37.  
  38. If it *is* chars, you can do
  39.  
  40.  { char *tmp;
  41.    tmp = malloc((nrows*sizeof(char *))+(nrows*ncols));
  42.    myarray = (char **) tmp;
  43.    tmp += nrows * sizeof(char *);
  44.    for (i=0;i<nrows;i++) { myarray[i] = tmp; tmp += ncols; }
  45.  }
  46.  
  47. but this depends on the alignment of char * being acceptable for char.
  48. For no other type is the analogous restriction known a priori to be
  49. satisfied, which is why this can be done only for chars.  (Unless, of
  50. course, it's in machine-specific code where you don't mind depending on
  51. the alignment behavior of your particular machine.)
  52.  
  53.                     der Mouse
  54.  
  55.                 mouse@larry.mcrcim.mcgill.edu
  56.