2 D array question

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Jul 2005
Posts: 1,221
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 137
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

2 D array question

 
0
  #1
Oct 2nd, 2006
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.
  1. // 2 D array
  2.  
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. int row, col, total_columns;
  10.  
  11. // two dimensional array in the form array[row][col]
  12. int iarray2[3][5] = { 1, 2, 3, 4, 5,
  13. 6, 7, 8, 9,10,
  14. 11,12,13,14,15 };
  15.  
  16. total_columns = sizeof(iarray2[0])/sizeof(int); // result = 5
  17. //total_rows = ??;
  18.  
  19. for(row = 0; row < 3 ; row++)
  20. {
  21. for(col = 0; col < total_columns; col++)
  22. {
  23. cout << row << " " << col << " " << iarray2[row][col] << endl;
  24. }
  25. cout << endl;
  26. }
  27.  
  28. // wait
  29. cin.get();
  30. return EXIT_SUCCESS;
  31. }
Reply With Quote Quick reply to this message  
Join Date: Sep 2006
Posts: 90
Reputation: Inanna is on a distinguished road 
Solved Threads: 6
Inanna's Avatar
Inanna Inanna is offline Offline
Junior Poster in Training

Re: 2 D array question

 
3
  #2
Oct 2nd, 2006
Take the total size and divide it by the size of one row.
  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5. int row, col;
  6. int total_columns;
  7. int total_rows;
  8.  
  9. int iarray2[3][5] = {
  10. 1, 2, 3, 4, 5,
  11. 6, 7, 8, 9, 10,
  12. 11,12,13,14,15
  13. };
  14.  
  15. total_columns = sizeof(iarray2[0])/sizeof(int); // result = 5
  16. total_rows = sizeof iarray2 / sizeof iarray2[0]; // result = 3
  17.  
  18. for(row = 0; row < total_rows; row++) {
  19. for(col = 0; col < total_columns; col++)
  20. std::cout<< row <<" "<< col <<" " << iarray2[row][col] <<'\n';
  21.  
  22. std::cout<<'\n';
  23. }
  24.  
  25. std::cout<<"Total columns: "<< total_columns <<'\n'
  26. <<"Total Rows: "<< total_rows <<'\n';
  27. }
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,221
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 137
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: 2 D array question

 
0
  #3
Oct 2nd, 2006
Thank you, makes sense! Had one of those days with a mental block!
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC