The information in this article applies to:
SUMMARYThe C language does not internally support dynamic memory allocation for two-dimensional arrays. Creating such a structure requires some programming to set it up; however, once created the elements can be referred to by the familiar double bracket ([][]) notation. There is memory overhead involved in creating the structure. This technique is platform-independent working in the MS-DOS, Windows, Windows NT, and OS/2 operating systems. MORE INFORMATIONFor the compiler to generate code for two-dimensional array element dereferencing, the number of columns of the array must be known at compile time. Therefore, it is possible to dynamically allocate a two-dimensional array if pointer declaration includes the "width" of the array. Below is a code fragment that illustrates this:
However, to give both dimensions of a two-dimensional array at run time the
array must be dynamically allocated. In this case, a dynamically allocated
two-dimensional array should be thought of as an array of one-dimensional
arrays. There is some memory overhead, however, which requires allocation
of an array of array pointers that is not necessary for statically defined
two-dimensional arrays. Despite the overhead, each element of the two-
dimensional arrays can be referenced with the bracket notation just as for
a statically defined two-dimensional array.
These are the steps for dynamically allocating a two-dimensional array:
Use _fmalloc() for MS-DOS and 16-Bit Windows to use the far/global
heap. Note for Windows: _fmalloc() is available to be used when
compiling with Microsoft C/C++ compiler versions 7.0, 8.0, and 8.0c.
Do not use GlobalAlloc and GlobalLock because this technique may use
up too many selectors for relatively small allocations.
Unlike a statically declared two-dimensional array, the rows are not contiguous with one another. But because this is an array of arrays it is possible to have a total structure larger than 64K without using huge pointers. If either the number of rows or the size of the rows is greater than 64K, then huge pointers are necessary. Sample Code
Additional query words: kbinf halloc
Keywords : kbLangC kbVC100 kbVC150 kbVC200 kbVC210 kbVC400 kbVC410 kbVC500 |
Last Reviewed: July 6, 1999 © 2000 Microsoft Corporation. All rights reserved. Terms of Use. |