I am currently working on this code. But there are some problems. First of all, if I run this code, it says array size in new-expression must be constant
. If I make the array arr[n]
, this error message does not appear. Also this code makes error message when it gets to the line cout << arr[i][j] << endl;
saying that invalid types 'int[int]' for array subscript.
I do not understand why this error message comes out because I made the array arr[n][n]
not arr[n]
.
What I want to make with this code is showing the magic-square for n*n if I type in n in the argument line.
This is my main.cc
#include <iostream>
#include <cstdlib>
#include <cstring>
#include "magic_square.h"
using namespace std;
int main(int argc, const char** argv) {
int n = atoi(argv[1]);
int *arr = new int[n][n];
if (n % 2 == 0 || n < 3)
return 0;
else
magicSquare(n, arr);
for (int i = 0, j = 0; i < n, j < n; i++, j++)
cout << arr[i][j] << endl;
delete[] arr;
return 0;
}
This is my magic_square.cc. I did not add magic_square.h
as it is only the declaration of the funtion void magicSquare(int n, int* arr)
.
#include <iostream>
#include "magic_square.h"
void magicSquare(int n, int* arr) {
for (int i = 0, j = n/2, num = 1; num <= n*n; num++) {
arr[i][j] = num;
if (num % n == 0) {
i++;
}
else {
i--, j++;
if (i < 0)
i = n - 1;
if (j > (n - 1))
j = 0;
}
}
}
~
Can anybody help me with this errors? Thanks in advance!