I am trying to assign values to each index in my 3x3 dimensional array. I initialized all the values to be 1 at the beginning, then set index[0][2] to be 2. however, somehow index[1][0] also attached to the value 2. then i tried to set [1][2] to 2, and [2][0] also set to value 2. I am not sure what is happening here?
void magicSquare (int param){
//param = 3
int volume = param - 1;
int squareArray[volume][volume];
int c = 0;
int d = 0;
for (int i = 0; i < param*param; i++) {
squareArray[c][d] = 1;
c +=1;
if (c == param) {
d +=1;
c = 0;
}
}
squareArray[0][2]= 2;
c = 0;
d = 0;
printf (" %d | ",squareArray[c][d]);
for (int i = 1; i < param*param; i++) {
c +=1;
if (c == param) {
d +=1;
c = 0;
printf ("\n %d | ",squareArray[c][d]);
}
else printf (" %d | ",squareArray[c][d]);
}
You declare your array as a 2x2 instead of 3x3.
param-1 (3-1) is assigned to volume, thus 2x2. Arrays start indexes from 0 and end at size-1. When declaring arrays, you declare the size, and then access elements from 0 to size-1.
Also, instead of using c and d, you can use nested for loops:
for(int i=0; i<param; ++i){ // will loop [0,param-1] or [0,param)
for(int j=0; j<param; ++j){ // same
arr[i][j] = 1;
}
}
Edit: I intentionally left out dynamic allocation as the OP is obviously a beginner.
If you always know the dimension of squares at compile-time, then you can write:
template<int param>
void magicSquare ()
{
int squareArray[param][param];
and leave the rest of your code as it is.
However, if param is not known until runtime then this doesn't work in standard C++. (Some compilers allow an extension but there are good reasons to avoid using such extensions).
Without getting into too much detail, a standard fix would be to write:
vector< vector<int> > squareArray(param, vector<int>(param));
Yes this is a bit ugly, but then you don't have to change the rest of your code. To enable this you'll need at the top of your file , #include <vector>, and also using std::vector; if you didn't already use namespace std.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With