Wednesday, 15 July 2015

Arbitrary and consistent change of array values for no apparent reason in c -



Arbitrary and consistent change of array values for no apparent reason in c -

the code below generates 3x3 matrix random integer values between 1-9. matrix generated in initsquare function , printed in printsquare function, unknown reason, value of bottom left value (*mptr[2][0]) changes value 2, regardless of previous value.

below output printing elements of filled matrix in line initsquare function, , below mysteriously altered square prints printsquare. notice alter of element 3 2. happens every generation of square, particular element beingness changed 2.

help in matter much appreciated.

421695378

4 2 1 6 9 5 2 7 8

void initsquare(magsquare_ptr mptr, int magicsquaresize){ int i, j, m, randomnum, numsquares; numsquares = (magicsquaresize * magicsquaresize); int check[numsquares][2]; for(m = 0; m < numsquares; m++){ check[m][0] = m; check[m][1] = 0; } for( = 0; < magicsquaresize; i++){ for(j = 0; j < magicsquaresize; j++){ randomnum = ((rand()%numsquares) + 1); while(check[randomnum-1][1] == 1){ randomnum = ((rand()%numsquares) + 1); } check[randomnum-1][1] = 1; *mptr[i][j] = randomnum; printf("%d", *mptr[i][j]); //test } }

}

void printsquare(magsquare_ptr mptr, int magicsquaresize){ int i, j; printf("\n"); for(i = 0; < magicsquaresize; i++){ for(j = 0; j < magicsquaresize; j++){ printf("%d " , *mptr[i][j]); } printf("\n"); }

}

c arrays pointers multidimensional-array dereference

No comments:

Post a Comment