Article ID: 104639
Article Last Modified on 12/2/2003
char (*array)[columns];
array = (char (*)[columns]) malloc(sizeof(char) * rows * columns);
if (array == NULL)
{
printf("Not enough memory!\n");
return;
}
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.
Array of Arrays of
Pointers Elements
------ ------------------------- -------
| | -->| | | | | | | . . . . . . . | |
------ ------------------------- -------
| | -->| | | | | | | . . . . . . . | |
------ ------------------------- -------
| | -->| | | | | | | . . . . . . . | |
------ ------------------------- -------
| | -->| | | | | | | . . . . . . . | |
------ ------------------------- -------
.
.
.
.
. ------------------------- -------
| | -->| | | | | | | . . . . . . . | |
------ ------------------------- -------
| | -->| | | | | | | . . . . . . . | |
------ ------------------------- -------
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.
/* Semi-pseudo code for a two-dimensional array of char's
* Note that this sample uses the far heap and uses far pointers.
* For 32-Bit Windows applications on Windows NT or Win32S or for
* OS/2, use malloc() and remove the _far keywords.
*/
char _far * _far * array;
unsigned int i;
unsigned int rows, columns; /* let's keep it within 64k */
/* Set the rows and columns to desired dimensions. */
rows = 8;
columns = 12;
array = (char _far * _far *) _fmalloc(sizeof(char _far *) * rows);
if (array == NULL)
{
printf("Not enough memory\n");
return;
}
for (i = 0; i < rows; i++)
{
array[i] = (char _far *) _fmalloc(sizeof(char) * columns);
if (array[i] == NULL)
{
printf("Not enough memory\n");
/* handle error, _free() the previously allocated rows */
return;
}
}
/* to use the array: array[row][column] */
array[0][1] = 'x';
/* etc. */
* To Free the memory used by the array
**
*/
for (i = 0; i< rows; i++)
_ffree(array[i]);
_ffree(array);
Additional query words: kbinf halloc
Keywords: kbinfo kblangc KB104639