home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.sys.mac.programmer
- Path: sparky!uunet!cs.utexas.edu!hermes.chpc.utexas.edu!news.utdallas.edu!corpgate!crchh327!crchh447!brunner
- From: brunner@crchh447.bnr.ca (James Brunner)
- Subject: Re: C array question
- Sender: news@news.rich.bnr.ca (news server)
- Message-ID: <C0rHtq.92E@news.rich.bnr.ca>
- Date: Tue, 12 Jan 1993 22:15:26 GMT
- Distribution: usa
- Reply-To: brunner@crchh447.bnr.ca (James Brunner)
- References: <C0prG1.AsC@plato.ds.boeing.com>
- Nntp-Posting-Host: crchh447
- Organization: BNR, Inc.
- Lines: 42
-
- In article <C0prG1.AsC@plato.ds.boeing.com>, housen@plato.ds.boeing.com (Kevin housen/.na) writes:
- |> I am making a jump from Pascal to C and have a simple question
- |> regarding creation of a 2D array at runtime. I want to create
- |> an array of floats r rows by c columns. A (non-Mac) friend
- |> suggests
- |>
- |> float **m /* this will be the 2D array */
- |> int r, c, count
- |>
- |> m = (float **) malloc (r*sizeof(float *));
- |> for (count=0, count < r, count++)
- |> m[count] = (float *) malloc (c * sizeof(float) );
- |>
- |> 1. If, instead of malloc, I want to use the Mac memory manager
- |> routines, does it matter if I use NewPtr or NewHandle (assuming
- |> I lock handles at the appropriate times)? Does malloc just
- |> call NewPtr?
-
- What this is doing is allocating an array of pointers and then for each pointer
- in the array, allocating another array. For example, for a 2x3 array, this is
- allocating one array of 2 pointers AND 2 arrays of 3 elements. Note that this
- is VERY different from declaring "int x[2][3]" which allocates one contiguous
- block of 6 ints (but can be doubly indexed).
-
- malloc is generally eqivalent to NewPtr. Can you do this with handles? Well,
- yes you can, but it gets a bit ugly. You would have a handle to an array of
- handles to arrays. If this is localized code or you just do this once for the
- program, I wouldn't hesitate to use NewPtr. If, however, you allocate and
- deallocate these things like mad all over your program (and in random order),
- I would consider the handle approach.
-
- |> 2. Can this be generalized to a 3D array?
-
- A three dimensional array could be done as:
- an array of pointers for the first dimension
- an array of pointers for each element of the second dimension
- an array of items of third level elements
- --
- ---------------------------------------------------------------------------
- Jim Brunner - (brunner@bnr.ca)
- All opinions are my own and have nothing whatsoever to do with BNR, NT,
- NTI, Bell Canada, or any of the BCE corporations or affiliates.
-