casting one dimension array as two dimension array in c++ -


i need create 2 dimensional array dynamically allocated memory (both dimensions set @ runtime), efficiency purposes want create 1 dimension version of contiguous allocated memory, , yet again somehow want use 2 dimensional array. there way use casting implement this. usage want implement below, not work. best,

int size = 4; int* arr = new int[size]; arr[0] = 10; arr[1] = 11; arr[2] = 12; arr[3] = 13; cout << (int[][2])arr[1][1] << endl; 

while think codor's solution in best compliance coding style of c++, share solution done in c-style.

#include <iostream>  typedef int (*pint2)[2]; //pint2 pointer array of 2 ints  int main() {     int arr[4] = { 0, 1, 2, 3 };     pint2 parr = (pint2)arr;     std::cout << parr[0][0] << std::endl;     std::cout << parr[0][1] << std::endl;     std::cout << parr[1][0] << std::endl;     std::cout << parr[1][1] << std::endl;      getchar();     return 0; } 

hope helps! (or @ least found interesting :/)

edit: , arrays of variable lengths!

#include <iostream>  int main() {     int arr[12] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };     const int sizeofarr = sizeof(arr)/sizeof(arr[0]); //number of elements in array      {         const int numofrows = 2; //number of rows         const int numofcolumns = sizeofarr/numofrows; //number of columns         typedef int (*pinta)[sizeofarr/numofrows]; //a 2d array of columns of 2          pinta parr = (pinta)arr;         for(int = 0; < numofrows; ++i)             for(int j = 0; j < numofcolumns; ++j)                 std::cout << parr[i][j] << std::endl;     }      {         const int numofrows = 3; //number of rows         const int numofcolumns = sizeofarr/numofrows; //number of columns         typedef int (*pinta)[sizeofarr/numofrows]; //a 2d array of columns of 3          pinta parr = (pinta)arr;         for(int = 0; < numofrows; ++i)             for(int j = 0; j < numofcolumns; ++j)                 std::cout << parr[i][j] << std::endl;     }      getchar();     return 0; } 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -