How do I pass an array to a constructor?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • svadhisthana7
    New Member
    • Feb 2012
    • 2

    How do I pass an array to a constructor?

    I want to pass an array to a constructor, but only the first value is passed--the rest looks like garbage.

    Here's a simplified version of what I'm working on:

    Code:
    #include <iostream>
    
    class board
    {
    	public:
    		int state[64];
    		board(int arr[])
    		{
    			*state = *arr;
    		}
    		void print();
    };
    
    void board::print()
    {
    	for (int y=0; y<8; y++)
    	{
    		for (int x=0; x<8; x++)
    			std::cout << state[x + y*8] << " ";
    		std::cout << "\n";
    	}
    }
    
    int main()
    {
    	int test[64] = {
    		0, 1, 2, 3, 4, 5, 6, 7,
    		1, 2, 3, 4, 5, 6, 7, 8,
    		2, 3, 4, 5, 6, 7, 8, 9,
    		3, 4, 5, 6, 7, 8, 9,10,
    		4, 5, 6, 7, 8, 9,10,11,
    		5, 6, 7, 8, 9,10,11,12,
    		6, 7, 8, 9,10,11,12,13,
    		7, 8, 9,10,11,12,13,14 };
    
    	board b(test);
    	b.print();
    
    	std::cin.get();
    	return 0;
    }
    Can someone explain why this doesn't work and how to properly pass an array? Notes: I don't want to copy the array. Also, I'm using MSVC++ 2010 Express.
  • svadhisthana7
    New Member
    • Feb 2012
    • 2

    #2
    I found the solution after posting to stackoverflow:

    "The name of an array is the address of the first element in it.

    Hence the line *state = *arr will set state[0] to arr[0].

    Since right now you have defined state as int state[64];, state is const pointer of type int whose address cannot be changed.

    You can change it to int *state; and then state = arr will work."

    Comment

    Working...