by Dan East » Oct 11, 2001 @ 11:46pm
I don't think I follow your question 100%. It appears you want to know how to dynamically create a 2 dimensional array at runtime. When it comes to true multidimensional arrays in C / C++, you have to specify the array bounds at compile time (one dimensional arrays do not have that limitation - you can dynamically allocate them any size you like). So, since we can dynamically create one dimensional arrays, we can create an array of pointers, then create an array of elements for each pointer:<br>[fixed]<br>//A dynamic "pseudo 2 dimensional" array of ints<br>//Create the main array of int pointers<br>int **MyArray=new int *[xLimit];<br><br>//Now for each int pointer, allocate a new<br>//array of ints which are the actual elements<br>for (int i=0; i<xLimit; i++)<br> MyArray[ i ]=new int[yLimit];<br><br>//Assign to the 5,3 element:<br>MyArray[5][3]=10;<br><br>//Clean up<br>//First delete all the actual elements<br>for (i=0; i<xLimit; i++)<br> delete []MyArray[ i ];<br>//Now delete the array of int pointers<br>delete []MyArray;<br>[/fixed]<br><br>Now, that acts like a multidimensional array in the way it is accessed (MyArray[xElement][yElement]), even though it is an array of arrays.<br> The caveats are that more code is required to allocate / deallocate, and although I haven't looked at the actual assembly that example generates compared to a real 2 dimensional array, it probably requires more instructions to access an element than accessing an element from a true multidimensional array.<br><br>Dan East