INF: Dynamic Memory Allocation for Two-Dimensional Arrays

ID Number: Q39976

4.00 5.00 5.10 6.00 6.00a 6.00ax | 5.10 6.00 6.00ax

MS-DOS | OS/2

Summary:

In Microsoft C versions 5.0, 5.1, 6.0, 6.0a, and 6.0ax, the best

method for dynamic memory allocation depends on the flexibility needed

and the amount of information concerning the array known at coding

time. The examples below set up two-dimensional arrays of characters.

Any element can be accessed with double subscripts, such as

array[i][j]. Symbols in uppercase letters are constants, while those

in lowercase letters are variables.

If one of the dimensions of the array is known, either of the

following two methods can be used. The first example creates more

overhead because of the number of malloc calls, but it is more

flexible because each malloc can be of a different size.

The following is the first example:

Sample Code 1

-------------

char *array[DIM_ONE];

int i;

for (i = 0; i < DIM_ONE; i++) {

array[i] = (char *)malloc(sizeof(char) * dim_two);

if (array[i] == NULL) {

printf("Not enough memory for columns in row %d!\n", i);

exit(1);

}

}

The following is the second example:

Sample Code 2

-------------

char *array[DIM_ONE];

int i;

array[0] = (char *)malloc(sizeof(char) * DIM_ONE * dim_two);

if (array[0] == NULL) {

printf("Not enough memory for columns!\n");

exit(1);

}

for (i = 1; i < DIM_ONE; i++) {

array[i] = (array[0] + (i * dim_two));

}

If neither of the dimensions is known at coding time, one of the

following two methods can be used. The pros and cons of each example

are the same as those for the previous examples.

The following is the third example:

Sample Code 3

-------------

char **array;

int i;

array = (char **)malloc(sizeof(char *) * dim_one);

if (array == NULL) {

printf("Not enough memory for rows!\n");

exit(1);

}

for (i = 0; i < dim_one; i++) {

array[i] = (char *)malloc(sizeof(char) * dim_two);

if (array[i] == NULL) {

printf("Not enough memory for columns in row %d!\n", i);

exit(1);

}

}

The following is the fourth example:

Sample Code 4

-------------

char **array;

int i;

array = (char **)malloc(sizeof(char *) * dim_one);

if (array == NULL) {

printf("Not enough memory for rows!\n");

exit(1);

}

array[0] = (char *)malloc(sizeof(char) * dim_one * dim_two);

if (array[0] == NULL) {

printf("Not enough memory for columns!\n");

exit(1);

}

for (i = 1; i < dim_one; i++) {

array[i] = (array[0] + (i * dim_two));

}

Additional reference words: 5.00 5.10 6.00 6.00a 6.00ax