Traditional way
In a C program, If we want to create an N-dimension array in heap (dynamically), we need to allocate the memory space step by step. For instance, if we want to create an 3-D array, we can use the code below.
1 | int ***create_3d_array(int len1,int len2,int len3) |
What you need to understand is the type of pointer in each step. If the type is wrong, it will incur unpredictable errors (may be in my future blog will talk about this issue). Therefore, for a novice in c/c++ programming, it is not easy to write a function to create N-dimension array.
An alternative way
Actually, we can allocate an one dimensional array with the same size. After that, if we want to access the N-dimension array, we first calculate the offset in the 1-D array. Let us take 3-D dimensional array as an example.
Assume the size of 3-D array is 8,9 and 10, respectively. Then we use the following code to create an one dimensional array with the same size.
1 | int *arr = (int *)malloc(sizeof(int)*8*9*10); |
After that, if we want to set the value at (3,4,5) to 10, we first calculate the offset. In other words, what is the corresponding position in the 1-D array for the element (3,4,5) in 3-D dimensional array. Through simple mathematic calculation, we can get the offset by calculate 3*9*10 + 4*10 + 5
. Generally, if we have a N-dimension array and the size of each dimensional is denoted as $(l_1,l_2,…,l_n)$, the offset for element $(i_1,i_2,…,i_n)$ is
You can use the program below to verify the correctness of this way.
1 |
|
Comparison
For the traditional way, it is much hard to initialize an N-dimension array. However, it is more efficient since we can directly access the element. For the alternative way, since we need to calculate the offset when access a certain element, it is applicable when the dimension is not very big, such as 2 or 3 dimensions.