Path: utzoo!yunexus!ists!helios.physics.utoronto.ca!news-server.csri.toronto.edu!cs.utexas.edu!samsung!sdd.hp.com!zaphod.mps.ohio-state.edu!brutus.cs.uiuc.edu!ux1.cso.uiuc.edu!csrd.uiuc.edu!usenet From: bruner@sp15.csrd.uiuc.edu (John Bruner) Newsgroups: comp.sys.mac.programmer Subject: Re: Need large array on Think C. Message-ID: <1990May31.170836.15902@csrd.uiuc.edu> Date: 31 May 90 17:08:36 GMT Article-I.D.: csrd.1990May31.170836.15902 References: <26645@<265986A9> <1232500002@ENS.Prime.COM> <1990May31.103925.13522@kth.se> Sender: usenet@csrd.uiuc.edu (news) Reply-To: bruner@sp15.csrd.uiuc.edu (John Bruner) Organization: CSRD, University of Illinois Lines: 46 In-Reply-To: d88-jwa@nada.kth.se (Jon W{tte) In article <1990May31.103925.13522@kth.se>, d88-jwa@nada (Jon W{tte) writes: >In article <1232500002@ENS.Prime.COM>, J.COOK@ENS.Prime.COM writes: > >> typedef char mytype[100][300]; >> globalarray = malloc( (unsigned long) sizeof(mytype) ); >> myarray[25][50] = 'a'; /* no overhead, direct in register */ > >This most definately won't work, since you NEVER have anything but >one-dimentional arrays in C. You'll have to go through the procedure >of allocating pointers to the various rows, and then allocating the >rows.... It is possible to dynamically allocate an N-dimensional array with a single call to malloc() if the last N-1 dimensions are known at compile time. Using this two-dimensional example, declare typedef char mytype[100][300]; char (*globalarray)[300]; and allocate it with globalarray = (char (*)[300])malloc((unsigned long)sizeof(mytype)); or, with typedefs typedef char char300[300]; typedef char300 mytype[100]; char300 *globalarray; globalarray = (char300 *)malloc((unsigned long)sizeof(mytype)); You can then say globalarray[25][50] = 'a'; The overhead you incur depends upon the storage class of "globalarray" (e.g., whether it is register) and the degree to which the compiler optimizes the code. However, it requires less memory and fewer levels of indirection than the alternate approach of setting up a one-dimensional array of pointers to the rows in the matrix. You must set up an array of pointers if the second dimension (300 in this case) is not a compile-time constant. -- John Bruner Center for Supercomputing R&D, University of Illinois bruner@uicsrd.csrd.uiuc.edu (217) 244-4476