How to print out 2d arrays with function in C++? -


i trying make function prints out 2 dimensional arrays. did 1 prints out 1d arrays.

 #include <iostream>  using namespace std;  void printarray (int thearray[],int sizeofarray); int main ()  { int array1[3] = {1,3,7}; int array2[5] = {123,5,23,2,324};  printarray(array1, 3); printarray(array2, 5);  }    void printarray (int thearray[],int sizeofarray){   (int x=0; x<sizeofarray; x++) {     cout<<thearray[x] <<" "; } cout<<endl;   } 

i wrote these codes printing out 2d arrays failed.

#include <iostream> using namespace std;  void printarray (int thearray[][],int sizeofrow, int sizeofcol);  int main ()  { int array[2][3] = {{1,3,7},{5,3,2}};  printarray(array, 2,3);   }  void printarray (int thearray[][],int sizeofrow, int sizeofcol){   (int x=0; x<sizeofrow; x++)       (int y=0; y<sizeofcol; y++) {          cout<<thearray[x][y] <<" "; } cout<<endl; } 

my compiler says array has incomplete element type 'int[]'. right codes printing out 2d arrays?

since array size has known during compile time, can use templates provide flexibility function.

template< typename t, size_t n, size_t m > void printarray( t(&thearray)[n][m]  ) {     ( int x = 0; x < n; x ++ ) {         ( int y = 0; y < m; y++ ) {             cout << thearray[x][y] << " ";         }     } }  printarray( array );  

this nicer since there no need pass dimension of array anywhere, work 3d, 4d array adding parameter template.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -