How do I return an Array?

This is a discussion on How do I return an Array? within the C++ Programming forums, part of the General Programming Boards category; I'm trying to return an array, or a pointer to an array. I've tried everything and cant get it to ...

  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    13

    How do I return an Array?

    I'm trying to return an array, or a pointer to an array. I've tried everything and cant get it to work. Will somone have a look at my code for me and show me what is wrong.

    All I have is a private array and I want to have a method in the class which will return the whole array, not one bit at a time.


    Code:
    class Board
    {
    public:
    	Board(void);
    	const int** getBoard ();
    private:
    	int theboard[4][4];
    };
    
     Board::Board(void)
    {
    	theboard;
    }
    
    
    const int** Board::getBoard () 
    { 
    	return &theboard; 
    }

  2. #2
    Registered User SKeane's Avatar
    Join Date
    Sep 2006
    Location
    England
    Posts
    234
    Why would you want to give something outside of the class direct access to a private data member?

  3. #3
    Registered User
    Join Date
    Oct 2006
    Posts
    13
    Quote Originally Posted by SKeane
    Why would you want to give something outside of the class direct access to a private data member?
    I mean I want to be able to read the value, not write to it.

  4. #4
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,069
    You should probably refine your class to return a location on the board, not the whole board itself. For instance
    Code:
    int Board::getBoardVal(const size_t x, const size_t y) const 
    {
        if (x < BOARD_MAX && y < BOARD_MAX)  // Assume BOARD_MAX is a constant size_t
            return theboard[x][y];
        else
            return theboard[0][0];   // Or however you want to handle this
    }
    That's the easiest, and in my opinion most logical way to read the board.

    By the way, I'm also a fan of allocating arrays dynamically in objects.
    Last edited by SlyMaelstrom; 10-03-2006 at 03:59 AM.
    Sent from my iPadŽ

  5. #5
    Registered User
    Join Date
    Oct 2006
    Posts
    13
    Quote Originally Posted by SlyMaelstrom
    You should probably refine your class to return a location on the board, not the whole board itself...That's the easiest, and in my opinion most logical way to read the board.
    I don't want to do this. I want to return the whole thing.

    If I do this everytime I have to have a loop to get the whole array bit by bit.

  6. #6
    Registered User SKeane's Avatar
    Join Date
    Sep 2006
    Location
    England
    Posts
    234
    You could try something like this ...

    Code:
    #include <iostream>
    
    static const unsigned int MAXROW = 4;
    static const unsigned int MAXCOL = 4;
    
    typedef int board [ MAXROW ][ MAXCOL ];
    
    class Board
    {
    public:
            Board(void);
            const board* getBoard ();
    private:
            board theboard;
    };
    
    Board::Board(void)
    {
        for (int c = 0; c < MAXCOL; c++)
        {
            for (int r = 0; r < MAXROW; r++)
            {
                theboard[r][c] = r * c;
            }
        }
    }
    
    const board * Board::getBoard ()
    {
            return(&theboard);
    }
    
    int main()
    {
        Board b;
        const board *pa;
    
        pa = b.getBoard();
    
        for (int c = 0; c < MAXCOL; c++)
        {
            for (int r = 0; r < MAXROW; r++)
            {
                std::printf("%d ", (*pa)[r][c]);
            }
            std::printf("\n");
        }
    
        return(0);
    }
    Or if the board is not of a fixed size, pass back a struct containg the address of the board and the board's dimensions.
    Last edited by SKeane; 10-03-2006 at 04:05 AM.

  7. #7
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,069
    Well then your other option is to pass an array to the function and copy theboard[][] to that array... Of course, that would require you to use a loop as well and those are real boring...

    You can't return an array... You can't very well get the address of the board, either because that would defeat the purpose of making it private wouldn't it? Whether you like loops or not, with reading arrays they're almost inevitable. So get used to them.

    Returning an array as SKeane did has logical flaws because all calls to getBoard() will refer to the same memory. For instance, if you were to, let's say, do
    Code:
    Board b;
    const board *b1, *b2;
    
    b1 = b.getBoard();
    b.setBoard(/*Some Values*/);  // Let's say we have a function to change the board
    b2 = b.getBoard();
    
    std::cout << "The first board:\n";
    for (int c = 0; c < MAXCOL; c++) {
        for (int r = 0; r < MAXROW; r++) {
                std::cout << (*b1)[r][c];
        }
        std::cout << '\n';
    }
    std::cout << std::endl;
    std::cout << "The second board:\n";
    for (int c = 0; c < MAXCOL; c++) {
        for (int r = 0; r < MAXROW; r++) {
                std::cout << (*b2)[r][c];
        }
        std::cout << '\n';
    }
    
    /* Both will print the same thing as both are refering 
        to the address of the changed board */
    This is why we pass arrays as arguements...

    Also, SKeane, don't be quick to assume that printf() is in <iostream>. It's defined in <cstdio> which isn't required by the standard to be included in <iostream>.
    Last edited by SlyMaelstrom; 10-03-2006 at 04:25 AM.
    Sent from my iPadŽ

  8. #8
    Registered User
    Join Date
    Oct 2006
    Posts
    13
    Thanks SKeane. That looks like it will work nicely.

    Yeah, passing the array would do it too, but I want to stay away from loops, although it would be much better to have the loop at the class end then having a new one each time.

    I was thinking I'd have to wrap the array in a class of its own and pass that if that makes sense.

    Thanks

  9. #9
    Registered User
    Join Date
    Oct 2006
    Posts
    13
    I'm still having trouble.

    The line typedef int board [ MAXROW ][ MAXCOL ]; means that now if we create something of type board is it an integer array of MAXROW by MAXCOL size?

    If I write int a=0; a=*pa[1][1] a doesn't seem to be what it should.

    Likewise, I can't use cout << a;. Why is this?

  10. #10
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,548
    > If I write int a=0; a=*pa[1][1] a doesn't seem to be what it should.

    Read the code again
    std::cout << (*b2)[r][c];

    Parentheses ARE important here

    > Likewise, I can't use cout << a;. Why is this?
    Because there is no way to know how much data a pointer points at, so you just get the pointer.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  11. #11
    Registered User SKeane's Avatar
    Join Date
    Sep 2006
    Location
    England
    Posts
    234
    Returning an array as SKeane did has logical flaws because all calls to getBoard() will refer to the same memory
    Presumably that isn't a "logical" flaw if that was what it was supposed to do in the first place?

    Note to self: Must stop using printf() in C++ examples. (It's not like I use it in the actual code I write!)

  12. #12
    Registered User
    Join Date
    Oct 2006
    Posts
    13
    Quote Originally Posted by Salem
    > If I write int a=0; a=*pa[1][1] a doesn't seem to be what it should.

    Read the code again
    std::cout << (*b2)[r][c];

    Parentheses ARE important here

    > Likewise, I can't use cout << a;. Why is this?
    Because there is no way to know how much data a pointer points at, so you just get the pointer.
    Yes they are. That was my problem.

    I take it that when using this the private array in the class still cannot be modified from outside the class, unless I write a Board class method to do so?

  13. #13
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,548
    I suggest you get to grips with this whole 'private data should be invisible to the outside world' idea.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  14. #14
    Registered User
    Join Date
    Oct 2006
    Posts
    13
    Quote Originally Posted by Salem
    I suggest you get to grips with this whole 'private data should be invisible to the outside world' idea.
    I'm trying. Tis why I came to ask for help

    Here's my situation. I did an electronic engineering degree which only had a very small C course. Now I'm doing a software development masters and am surrounded people with CSD degrees & professionals returning to increase their edge and what not. So to say i'm in the deep end is putting it mildly. But I'll get there, sure I learned to ride a bike.

  15. #15
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    Quote Originally Posted by Mr. Flibble
    If I do this everytime I have to have a loop to get the whole array bit by bit.
    In general, whenever you USE the array (e.g. when you want to print it out, or use the board to draw the screen, etc.) you're going to need to loop element by element through the array anyway, regardless of whether your function returns the whole array or not.

    When you have something like a game board, looping through each element is unavoidable.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. is it ok like that?
    By ExDHaos in forum C++ Programming
    Replies: 8
    Last Post: 05-23-2009, 09:02 AM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. Another weird error
    By rwmarsh in forum Game Programming
    Replies: 4
    Last Post: 09-24-2006, 10:00 PM
  4. Pong is completed!!!
    By Shamino in forum Game Programming
    Replies: 11
    Last Post: 05-26-2005, 10:50 AM
  5. opengl help
    By heat511 in forum Game Programming
    Replies: 4
    Last Post: 04-05-2004, 01:08 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21