How Do I Create a 2-Dimensional Array Dynamically in ANSI C?Primary Software: LabWindows/CVI Development Systems>>Full Development System
Primary Software Version: 7.0
Primary Software Fixed Version: N/A
Secondary Software: N/A
Problem: I need to create a 2D array to hold data, but I will not know the dimensions of the array until the program is running. How can I dynamically create the 2D array at runtime?
Solution: There are two primary ways to dynamically create a 2D array. The following two pieces of code will dynamically create an MxN 2D array, where M is the size of the first dimension, and N is the size of the second dimension. In the cases shown below it will be a 20x10 2D array.
Pointer to a Pointer to Data Method
When creating a dynamic 2D array using the pointer to a pointer to data method, first create a 1D array dynamically by declaring a pointer and allocating a variable amount of memory to that pointer. The pointer then points to the first element of the array, and the data that it points to can be retrieved by using array, array, etc.
You can think of a 2D array as an array of 1D arrays. So memory is first allocated to 'table' for an array of pointers. Each of these pointers then has memory allocated to them to hold the data of the array. You can then access data using array notation table, table, etc.
Pointer to Data Method
When creating a dynamic 2D array using the pointer to data method, all you are doing is creating a 1D array that has enough space for the entire 2D array. When creating a 2D array using this method you can no longer use the conventional way of accessing each individual element (table[x][y]) instead you have to calculate where the element is in the 1D array. If you are looking for the element at row 11 column 3 then multiply 11 by the number of rows (20) and add 3. In general always multiply the row of the element you want by the number of rows and then add the column of the element you want.
Which of these two methods you should use depends on your application. If you are calling a function that asks for a 2D array, but requests a pointer to data then use the pointer to data method. However, if the function wants a pointer to a pointer to data then use the pointer to a pointer to data method. The only other main differences between these two methods are the way the individual elements are accessed (table[x][y] vs. table[x*M+y]) and how much code is required to free the allocated memory after use.
Report Date: 03/11/1998
Last Updated: 12/09/2004
Document ID: 17ADRTTI