Thread: passing two dimensional arrays

  1. #1
    Registered User Nova_Collision's Avatar
    Join Date
    Feb 2003
    Posts
    40

    passing two dimensional arrays

    Okay, here's what I've got :

    int **getIntArray()
    {
    int **theArray[240][2];
    **theArray[0][0] = 0;
    return **theArray;
    }


    void main()
    {
    int **theArray = getIntArray();
    }

    Of course that's not the entire program, but anyway, it compiles fine, but crashes whenever I try to run it. I know it has something to do with either my method or when I call the method because as soon as I comment out the line :
    int **theArray = getIntArray();
    The program no longer crashes. I must be missing something in how two dimensional arrays are handled, so any help would be greatly appreciated.
    When in doubt, empty your magazine - Murphy's Laws Of Combat #7

  2. #2
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    Unless you want 480 pointers to pointers then your syntax is off, that's the first thing, the second is that you can't return a pointer to a local variable, it goes out of scope and the pointer isleft dangling :-) The solution is to use a dynamically allocated array
    Code:
    int **getIntArray()
    {
      int **theArray;
    
      theArray = new int *[240];
      for (int i = 0; i < 240; i++)
      {
        theArray[i] = new int[2];
      }
    
      theArray[0][0] = 0;
    
      return theArray;
    }
    
    void main()
    {
      int **theArray = getIntArray();
    }
    *Cela*

  3. #3
    Registered User Nova_Collision's Avatar
    Join Date
    Feb 2003
    Posts
    40
    Thanks, Cela. You have no idea how relieved I am to finally get that working. Even my programming teachers at the tech school I go to didn't know how to make it work. Kinda makes me wonder if I'm in the right school, eh?........
    When in doubt, empty your magazine - Murphy's Laws Of Combat #7

  4. #4
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    >>Kinda makes me wonder if I'm in the right school, eh?........
    I'd wonder that too :-)
    *Cela*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointers and multi dimensional arrays
    By andrea72 in forum C++ Programming
    Replies: 5
    Last Post: 01-23-2007, 04:49 PM
  2. Passing 2 dimensional arrays to functions
    By homeyg in forum C++ Programming
    Replies: 7
    Last Post: 01-09-2005, 03:16 PM
  3. Replies: 6
    Last Post: 04-26-2004, 10:02 PM
  4. Passing 2 dimensional Arrays to functions
    By aresashura in forum C++ Programming
    Replies: 4
    Last Post: 12-18-2001, 12:59 AM
  5. Two dimensional arrays
    By Jax in forum C Programming
    Replies: 1
    Last Post: 11-07-2001, 12:53 PM