I wrote this little code to test a 2 dimensional array. Given the array array[row][col] I can find total_columns, but I am at loss to figure out total_rows.

// 2 D array

#include <iostream>

using namespace std;

int main()
{
  int row, col, total_columns;
  
  // two dimensional array in the form array[row][col]
  int  iarray2[3][5] = { 1, 2, 3, 4, 5,          
                         6, 7, 8, 9,10,
                        11,12,13,14,15 };

  total_columns = sizeof(iarray2[0])/sizeof(int);  // result = 5
  //total_rows = ??;
    
  for(row = 0; row < 3 ; row++)
  {
    for(col = 0; col < total_columns; col++)
    {
      cout  << row << "  " << col << "  " << iarray2[row][col] << endl; 
    }
    cout << endl;
  }
  
  // wait
  cin.get();
  return EXIT_SUCCESS;
}

Recommended Answers

All 2 Replies

Take the total size and divide it by the size of one row. :)

#include <iostream>

int main()
{
  int row, col;
  int total_columns;
  int total_rows;
  
  int  iarray2[3][5] = {
    1, 2, 3, 4, 5,          
    6, 7, 8, 9, 10,
    11,12,13,14,15
  };

  total_columns = sizeof(iarray2[0])/sizeof(int);  // result = 5
  total_rows = sizeof iarray2 / sizeof iarray2[0]; // result = 3
    
  for(row = 0; row < total_rows; row++) {
    for(col = 0; col < total_columns; col++)
      std::cout<< row <<"  "<< col <<"  " << iarray2[row][col] <<'\n'; 

    std::cout<<'\n';
  }

  std::cout<<"Total columns: "<< total_columns <<'\n'
    <<"Total Rows: "<< total_rows <<'\n';
}
commented: good one, keep it up [~s.o.s~] +5
commented: Helps-[Grunt] +2
commented: Down to Earth +5

Thank you, makes sense! Had one of those days with a mental block!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.