Thread: dynamic allocation of multidimensional array

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    22

    dynamic allocation of multidimensional array

    I am trying to allocate memory for a 2 dimensional array of size declared by the user but am not quite sure how to do this. I read several forums about it to generate the code I have so far but am getting errors about have invalid types int[int] for array subscript. Any help would be appreciated THANKS.

    Code:
    #include <iostream>
    #include <vector>
    using namespace std;
    
    void MagicSquare ( int ptr, int n );
    void DisplaySquare ( int ptr, int n );
    
    int main(void)
    {
    int order, **ptr;
    
    cout <<"This program will create a magic square of an odd order\n";
    cout <<"Please enter the order number you would like:\n";
    cin >> order;
    ptr = new int *[order]; //allocates a new array of pointers to int type
    for(int i=0; i<order; ++i)
        ptr[i]=new int[order]; //allocates space for each pointer making second dimension
    if (order%2==1)
        MagicSquare( **ptr, order );
        else{
            delete []ptr;
            cout <<"order cannot be even\n";
        }
        DisplaySquare( **ptr, order );
    }
    void MagicSquare ( int ptr, int n )
    {
    int max = n * n;
    int i=0;
    int j=n/2;     // start position
    
      for (int k=1; k<=max; ++k)
      {
        ptr[i][j]= k;
    
        i--;
        j++;
    
        if (k%n == 0)
        {
          i += 2;
          --j;
        }
        else
        {
          if (j==n)
            j -= n;
          else if (i<0)
            i += n;
        }
      }
    }
    void DisplaySquare( int ptr, int n)
    {
      for (int i=0; i<n; i++)
      {
        for (int j=0; j<n; j++)
          cout << ptr[i][j] << "\t";
    
        cout << "\n\n\n\n";
      }
    
    }

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    You're creating the 2D array properly, but you're calling and declaring your subroutines wrong:
    Code:
    MagicSquare(ptr, order);
    ...
    void MagicSquare(int **ptr, int n)
    
    // same for display func
    ptr is a bad name. square is a better one.

    And your code code be formatted better.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by lancehumiston
    I am trying to allocate memory for a 2 dimensional array of size declared by the user but am not quite sure how to do this.
    There are a few ways to do this, but quite possibly the easiest (though slightly space inefficient) is to #include <vector> and use a std::vector of vectors:
    Code:
    vector<vector<int> > magic_square(order, vector<int>(order));
    Now you just access magic_square[i][j]. Since this is a standard container, you do not need to do manual memory management. Of course, your functions have to change accordingly, e.g.,
    Code:
    void DisplaySquare(const std::vector<std::vector<int> >& magic_square);
    A typedef can help.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    It's also possible to use a single dimensional array or vector and mimic a 2D array or vector like this:
    Code:
    v[y * order + x]
    That way you can allocate it as a 1D array or order*order size.
    Easier to allocate. More space efficient. Faster to access (I think). Easier to delete.
    The only downside is you can't access it like v[x][y].

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by oogabooga
    The only downside is you can't access it like v[x][y].
    Of course, a function can be written to approximate such access, especially since it can be unit tested to avoid mistakes such as writing y * order + x instead of x * order + y, given a row-major order
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Or you could use Boost.MultiArray, which wraps all this stuff up in a nice class.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic array Allocation
    By deepak_j in forum C Programming
    Replies: 3
    Last Post: 08-17-2009, 07:18 AM
  2. Passing multidimensional/dynamic array to function
    By epyfathom in forum C Programming
    Replies: 2
    Last Post: 04-02-2009, 05:39 PM
  3. dynamic 2D array allocation
    By deprekate in forum C Programming
    Replies: 5
    Last Post: 03-03-2009, 04:25 AM
  4. dynamic allocation of 2d array
    By owi_just in forum C Programming
    Replies: 4
    Last Post: 05-09-2005, 12:50 AM
  5. dynamic allocation of multidimensional arrays in c++
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 02-15-2002, 04:18 PM

Tags for this Thread