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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#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? I'm using MSVC++ 2010 Express.
pass the address

and in your constructor accept it properly...

Last edited on
My understanding is that arrays are automatically passed as pointers. Did you mean I should pass by reference?

If I change line 7 to board(int (&arr)[64]), the result is the same. What am I missing?

Edit: I did some more reading online and found some people saying that arrays are automatically passed as references, and some saying they're passed as pointers. So now I'm not sure which is the case. I tried changing line 7 to board(int *arr), and again I got the same result.
Last edited on
How about changing line 9 to:
for (int i = 0; i < 64; i++) state[i] = arr[i];

The reason is that *arr is effectively the same as arr[0]. and *arr+i is effectively the same as arr[i].
Last edited on
Thank you, but I don't want to copy the array.

I think I can see why it's only passing the first value though, according to your explanation.

As far as I understand, I'm trying to assign the address of test to state so they both point to the same array, and apparently I'm not doing it correctly or I'm misunderstanding something.
Last edited on
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."
Topic archived. No new replies allowed.