Pointer of an array in recursive function

closed account (E3h7X9L8)
I've made queens problem , it works if I declare the array in which I calculate the solution global, but if I try to dynamically allocate it and pass it to the recursive function using pointers it just prints empty solution infinitely...

I'm trying for hours to figure out whats the problem...

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
 #include <iostream>
using std::cout;
using std::endl;

#include <cmath>
using std::abs;

#define N 5

void dame(int *v, int k);
void print(int *v);

int main()
{
	int *v = new int[N];
	dame(&v[0], 0);

        delete []v;
	return 0;
}

void dame(int *v, int k)
{
	if (k == N)
		print(v);
	else
	{
		for (int i = v[k]; i < N; i++)
		{
			v[k] = i;
			bool valid = true;
			for (int j = 0; j < k; j++)
			{
				if ( ( abs(v[k] - v[j]) == abs(k - j) ) || 
					(v[k] == v[j]) )
					valid = false;
			}

			if (valid == true)
				dame(v, k + 1);
			v[k] = 0;
		}
	}
}

void print(int *v)
{
	for (int i = 0; i < N; i++)
	{
		
		for (int j = 0; j < N; j++)
		{
			cout << char(179);
			if (j == v[i])
				cout << "D";
			else
				cout << " ";
		}
		cout << endl;
		
		for (int k = 0; k < 2 * N - 1; k++)
		{
			if (k % 2 == 0)
				cout << char(197);
			else
				cout << char(196);
		}
		cout << endl;

	}
	cout << endl;
}
If you were using a global array, all the elements would be initialized to zero. That isn't the case here. All elements of your newed array are random junk.

To fix it: int *v = new int[N]();
closed account (E3h7X9L8)
thanks, seems that was the problem
Topic archived. No new replies allowed.