Magic Square Help?

I'm a bit lost as to why my program is getting an error code as it runs. It will compile I get an error memory violation code. The goal is to let the user enter an odd number greater than 3 and print out a magic square of those dimensions. Any help or guidance? I need to use the dynamic array.

Here's what I have so far..


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

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	int rows, columns;
	cout << "Please enter a single integer for the magic square's dimensions: ";
	cin >> rows;
	columns = rows;
	int userChoice = rows;

	//Declare the dynamic array

	int **magicSquare;
	magicSquare = new int *[rows];
	for (int ix = 0; ix++ < rows; ++ix)
		magicSquare[ix] = new int[columns];

	//Assigning values to magic square
	int p1 = (userChoice / 2);
	int p2 = (userChoice -1);
	for (int ix = 1; ix <= (userChoice * userChoice);)
	{
		if (p1 == -1 && p2 == userChoice)
		{
			p1 = userChoice - 2;
			p2 = 0;
		}
		else
		{
			if (p2 == userChoice)
				p2 = 0;
			if (p1 < userChoice)
				p1 = userChoice - 1;
		}
		if (magicSquare[p1][p2])
		{
			p2 -= 2;
			p1++;
		}
		else
			magicSquare[p1][p2] = ix++;
		p1++;
		p2++;
	}
	for (int ix = 0; ix < userChoice; ix++)
	{
		for (int iy = 0; iy < userChoice; iy++)
			cout << magicSquare[rows][columns] << " " << endl;
	}
	//Delete the array
	for (int ix = 0; ix < columns; ++ix) {
		delete[] magicSquare[ix];
	}
	delete[] magicSquare;
}
line 18: for (int ix = 0; ix++ /*¿?*/ < rows; ++ix)
Whoops, that's one problem. However I'm still getting the error when I try to run the program with some values.

Specifically an unhanded exception and access violation..
debugger, backtrace
valgrind is quite useful too. By instance, it detects use of uninitialized variables, bad deletes and out of bounds access.


1
2
	for (int ix = 0; ix < rows; ++ix)
		magicSquare[ix] = new int[columns]();
so each cell gets initialized to 0


35
36
37
38
39
if (p1 < userChoice)
	p1 = userChoice - 1;
//...
p1++; //line 45
p2++;
`p1' should always be less than userChoice or else you'll have out of bound access.
But after line gets 36 executed, you increment `p1' in line 45 and break that.
Not sure what was your intention there.

you also let the index become negative


line 51 is trying to access out of bounds (you are printing the same cell over and over again)
Topic archived. No new replies allowed.