2 D array question
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;
}
bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184
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';
}
Inanna
Junior Poster in Training
90 posts since Oct 2006
Reputation Points: 53
Solved Threads: 6
Thank you, makes sense! Had one of those days with a mental block!
bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184