Thread: How can I dynamically make matrices

  1. #1
    Registered User rmullen3's Avatar
    Join Date
    Nov 2001
    Posts
    330

    How can I dynamically make matrices

    I know this question is relatively simple... but how can what would be the syntax for making an array of pointers to arrays to make a matrix, dynamically? ie the width/height is not known at run-time

    And what would be the syntax for accessing an element of this matrix at x,y? Thanks : )

  2. #2
    Fingerstyle Guitarist taylorguitarman's Avatar
    Join Date
    Aug 2001
    Posts
    564
    Code:
    #include <iostream>
    using namespace std;
    
    int main( int argc, char **argv ) {
    
      /* 2-dimensional dynamic matrix */
      int **dynamicMatrix = NULL;
    	
      /* variables to hold the number of rows and columns in the matrix */
      int numRows    = 0;
      int numColumns = 0;
    
      /* loop counters */
      int row    = 0;
      int column = 0;
    
      /* prompt for rows and columns */
      cout << "Enter number of rows: ";
      cin >> numRows;
    
      cout << "Enter number of columns: ";
      cin >> numColumns;
    
      /* create the rows of the matrix */
      dynamicMatrix = new int*[ numRows ];
    	
      /* assume each row will have the same number of columns
       * note: each row could have a different number of columns */
      for( row = 0; row < numRows; row++ ) {
    
        dynamicMatrix[ row ] = new int[ numColumns ];
      }
    
      /* set all the values to 5 */
      for( row = 0; row < numRows; row++ ) {
    	
        for( column = 0; column < numColumns; column++ ) {
    
          dynamicMatrix[ row ][ column ] = 5;
        }
      }
    
      /* display the matrix */
      for( row = 0; row < numRows; row++ ) {
    	
        for( column = 0; column < numColumns; column++ ) {
    
          cout << dynamicMatrix[ row ][ column ];
        }
    
        cout << endl;
      }
    
      return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Establishing 'make clean' with GNU make
    By Jesdisciple in forum C Programming
    Replies: 9
    Last Post: 04-11-2009, 09:10 AM
  2. How to make a Packet sniffer/filter?
    By shown in forum C++ Programming
    Replies: 2
    Last Post: 02-22-2009, 09:51 PM
  3. Question about atheists
    By gcn_zelda in forum A Brief History of Cprogramming.com
    Replies: 160
    Last Post: 08-11-2003, 11:50 AM
  4. 'functions' in make?
    By mart_man00 in forum C Programming
    Replies: 1
    Last Post: 06-21-2003, 02:16 PM
  5. Replies: 6
    Last Post: 04-20-2002, 06:35 PM