Thread: Returning two-dimensional array in C++

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User Drogin's Avatar
    Join Date
    Oct 2005
    Location
    Norway
    Posts
    105

    Returning two-dimensional array in C++

    Hi!
    I want to make a get() function for a two-dimensional array in my class.
    Like this:
    Code:
    class MyClass {
      public:
      getArray();  // <-----How do I define and decleare this function?
    
      private:
      int array[5][5];
    };

    So, I would like to use the function like this:

    Code:
    int main() {
    MyClass foo;
    
    // *Decleare the array somehow* <-------how would I do this?
    array = foo.getArray();
    return 0;
    }

  2. #2
    Registered User
    Join Date
    Jun 2008
    Posts
    15
    I'm guessing you want to use something like:
    Code:
    array[1][3] = 40;
    I may not know how to achieve that, but you could instead. workaround is simply using int* as the return type/declaration type. Then add getWidth() and getHeight() functions.

    Code:
    array[1 * getHeight() + 3]
    Assuming you have differing dimensions:

    Code:
    int arr[H][W];
    arr[y][x] = v;
    then the native index:
    Code:
    arr[ y * H + W ] = v;

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    std::vector< std::vector<type> > foo()
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #4
    Registered User
    Join Date
    Jun 2008
    Posts
    15
    Actually, there was another post just now, with a similar problem, so with no life of mine i made a sample for you:

    Code:
    typedef int array2d [5][5];
    
    array2d arr;
    
    array2d* get_arr()
    {
    	return &arr; 
    }
    
    int main()
    {
    	int i;
    	int *t;
    
    	t = (int*)(arr);
    	for (i = 0; i < 25; i++) {
    		t[i] = i;
    	}
    	printf("%d\n", arr[3][2]);
    
    	array2d *a1;
    	a1 = get_arr();
    
    	printf("%d\n", (*a1)[3][2]);
    
    	return 0;
    }
    thank this guy King Mir:
    http://cboard.cprogramming.com/showthread.php?t=103106

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Use a vector. It's far easier.
    No global variables either.
    This is C++, not C...
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    The larch
    Join Date
    May 2006
    Posts
    3,573
    A vector of vectors may have too much overhead to be a replacement for small multidimensional stack array. (I believe there are cases where it is justified not to want dynamic allocations.)

    By the way, do you want to return a copy of the array?

    In that case, it might be meaningful to use an out parameter (the contents are copied to a suitable array provided by the caller).

    If you don't want a copy, then you might try returning a pointer to pointer (int**).

    -----
    Best advice depends on what exactly you are doing this for...
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by anon View Post
    A vector of vectors may have too much overhead to be a replacement for small multidimensional stack array. (I believe there are cases where it is justified not to want dynamic allocations.)

    By the way, do you want to return a copy of the array?

    In that case, it might be meaningful to use an out parameter (the contents are copied to a suitable array provided by the caller).

    If you don't want a copy, then you might try returning a pointer to pointer (int**).

    -----
    Best advice depends on what exactly you are doing this for...
    Returning a pointer to pointer won't work, since you loose the dimension of the array. You will need to indicate at least the last dimension of the array.

    gcc (and g++) doesn't seem to allow functions returning arrays.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    Registered User Drogin's Avatar
    Join Date
    Oct 2005
    Location
    Norway
    Posts
    105
    I can give you a very simple Java-verison of what I want.
    I will comment it well, so non-java people can read it.

    So, I would like a C++ verison of this java-code:
    Code:
    class MyClass {
        private int[][] iPointer = new int[5][5]; // This makes a new array of int, and let iPointer point to it
    
        // This is the get-function. It returns a pointer to the array
        public int[][] getArray() {
            return iPointer;
        }
    }
    
    
    class MainClass {
        public static void main(String[] args) { // This is the java int main()
            MyClass myclass = new MyClass(); // Run the above class.
            int[][] anotherPointer; // Decleare a pointer that should be pointing to a 2-dimensional int array
            anotherPointer = myclass.getArray(); // Set the pointer to point to the array returned
    
    
            // Then, I want to be able to do this, on the array returned.
            // (This pointer points to the iPointer member in myclass)
            anotherPointer[0][0]=5;
            anotherPointer[0][1]=3;
        }
    }

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    You should be able to return a pointer to an array in a class. Let me work on it for few minutes.

    Not very pretty:
    Code:
    #include <iostream>
    
    typedef int myarray[5][5];
    
    class myclass
    {
        myarray arr;
    
    public:
        myclass() {
    	for(int i = 0; i < 5; i++)
    	{
    	    for(int j = 0; j < 5; j++)
    		arr[j][i] = i * j;
    	}
        }
        friend std::ostream &operator<<(std::ostream &os, const myclass &c);
        myarray * getArray()
    	{
    	    return &arr;
    	}
    
    
    };
    
    std::ostream &operator<<(std::ostream &os, const myclass &c) 
    {
        for(int i = 0; i < 5; i++)
        {
    	for(int j = 0; j < 5; j++)
    	    os << c.arr[j][i] << " ";
    	
    	os << std::endl;
        }
        
        return os;
    }
    
    
    
    int main()
    {
        myclass c;
        int (*p)[5][5];
       
        std::cout << c;
      
        p = c.getArray();
        for(int i = 0; i < 5; i++)
        {
    	for(int j = 0; j < 5; j++)
    	    std::cout << (*p)[j][i] << " ";
    	std::cout << std::endl;
        }
        return 0;
    
    }
    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    If you want Java approach, it's easy if you use std::vector. You can return std::vector, so essentially, you can return an array that way.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User Drogin's Avatar
    Join Date
    Oct 2005
    Location
    Norway
    Posts
    105
    Well, I know.
    But there should be a way to do this without vectors too...?
    Let's say I would use this code-block inside a game-loop, using vectors. That would hurt. If you catch my drift

  12. #12
    Banal internet user
    Join Date
    Aug 2002
    Posts
    1,380
    Quote Originally Posted by Elysia View Post
    If you want Java approach, it's easy if you use std::vector. You can return std::vector, so essentially, you can return an array that way.
    Hi Elysia,
    This would work well and all, but it really isn't going to help them understand why you can't "return a 2d array" in C++.

    When people learn C++ they generally learn about how strings are represented in memory as null-terminated byte arrays before they learn to use the std::string class, right? Same idea here, IMO.

  13. #13
    Registered User Drogin's Avatar
    Join Date
    Oct 2005
    Location
    Norway
    Posts
    105
    Okay folks, thanks a lot for your time, and the wonderful replies.
    laserlight's solution worked fine, so that was all I needed, thanks a ton



    To Elysia: I'm sorry I couldnt adress you earlier, I was kinda busy.
    I am not anti-vector. Using vectors would surely pose no problem for me for the use I want, and it was an excelent suggestion.

    However, I would also like to know how to make it without vectors, in case I would ever need to do that. For example because of memory or speed concerns.
    And just out of curiosity. I've been trying for hours to get it to work, so I wanted to see the "correct" solution.

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by BMJ View Post
    When people learn C++ they generally learn about how strings are represented in memory as null-terminated byte arrays before they learn to use the std::string class, right? Same idea here, IMO.
    Oh, but was not under impression that it was to learn, but rather to get it working with a good solution.

    Quote Originally Posted by Drogin View Post

    To Elysia: I'm sorry I couldnt adress you earlier, I was kinda busy.
    I am not anti-vector. Using vectors would surely pose no problem for me for the use I want, and it was an excelent suggestion.

    However, I would also like to know how to make it without vectors, in case I would ever need to do that. For example because of memory or speed concerns.
    And just out of curiosity. I've been trying for hours to get it to work, so I wanted to see the "correct" solution.
    I see.
    But you could have mentioned it earlier.
    Anyway, no harm done.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Then use references.
    Create the vector inside the class and let getArray return a reference to it.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Multi dimensional array
    By $l4xklynx in forum C Programming
    Replies: 7
    Last Post: 01-03-2009, 03:56 AM
  2. Replies: 6
    Last Post: 11-09-2006, 03:28 AM
  3. problem returning array from function(among others)
    By Calef13 in forum C++ Programming
    Replies: 30
    Last Post: 10-30-2006, 04:26 PM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Replies: 5
    Last Post: 11-20-2001, 12:48 PM