home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!usc!cs.utexas.edu!hermes.chpc.utexas.edu!news.utdallas.edu!corpgate!crchh327!crchh447!brunner
- From: brunner@crchh447.bnr.ca (James Brunner)
- Subject: Re: Dynamic Multidimensional Array Allocation in C++
- Sender: news@news.rich.bnr.ca (news server)
- Message-ID: <C0EE0J.Iv@news.rich.bnr.ca>
- Date: Tue, 5 Jan 1993 20:24:19 GMT
- Reply-To: brunner@crchh447.bnr.ca (James Brunner)
- References: <C0C68I.MA7@dcs.ed.ac.uk> <C0Cw7r.72t@dcs.ed.ac.uk>
- Nntp-Posting-Host: crchh447
- Organization: BNR, Inc.
- Lines: 48
-
- In article <C0Cw7r.72t@dcs.ed.ac.uk>, tk@dcs.ed.ac.uk (Tommy Kelly) writes:
- |> In article <C0C68I.MA7@dcs.ed.ac.uk> tk@dcs.ed.ac.uk (Tommy Kelly) writes:
- |> >How do I implement a dynamically configurable two dimensional array in C++?
- |> >
- |> >For one dimension its easy, but doing:
- |> >
- |> >my_type *my_type_var = new my_type[a][b];
- |>
- |> What I'm doing at the moment is explicitly creating a vector of vectors like:
- |>
- |> My_type **my_type_var = new My_type*[a];
- |> for(int i=0; i<b; i++) {
- |> my_type_var[i] = new My_type[b];
- |> }
- |>
- |> I can then access the array my_type_var[a][b] as normal.
- |> But it seems kinda inelegant. Maybe I expect too much from C++...
-
- Actually, your method is very elegant. The problem is that array access is
- greatly a function of the compiler. To access element [2][3] in a [][7] array,
- the compiler creates code that does this:
-
- element address = (start of array) + ((2 * 7) + 3) * (element size))
-
- or more generally, to access element [x][y]:
-
- element address = (start of array) + ((x * 7) + y) * (element size))
-
- Notice that the size of the lower dimensions are compiled in (the element size(
- is as well).
-
- By creating an array of pointers to one dimensional arrays, you can access it
- (syntax wise) like a two dimensional array, but the compiler generates this:
-
- pointer address = (start of array) + x * (pointer size)
- element address = (dereferenced pointer address) + y * (element size)
-
- There is no need for the compiler to know any of the dimensions in advance.
-
- Of course other benefits depend on how the 2 dimensional array is to be used.
- If for example you were mapping a terminal screenful of characters, with your
- method, a scroll operation would only involve shifting the pointers and clearing
- the last line. Must faster than moving all of the 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.
-