Search code examples
carraysmagic-square

Printing 2D arrays prints junk(Magic Square)


I am trying to write a C program to print a magic square. However, I am encountering an error when building the square. Could anyone help to figure out what is causing these bugs? The following is my relevant code, and my output:

Code:

  int main(void) {
      int size = 0;
      int r, c;
      int i = 1;

      printf("What is the size of the square: ");
      scanf("%d", &size);

      int square[size][size];
      int range = size * size;
      r = 0;
      c = size/2;

      do {
          square[r][c] = i;

          i++;
          r--;
          c++;

          if ((r == -1) && (c == size)) {
              r = r + 2;
              c--;
          } else if (r == -1) {
              r = size - 1;
          } else if (c == size) {
              c = 0;
          } else if (square[r][c] != 0) {
              r = r + 2;
              c--;
          }
      } while (i < range);

      for (r = 0; r < size; r++) {
          for (c = 0; c < size; c++) {
              printf("%d \t", square[r][c]);
          }
          printf("\n");
      }

      return 0;
  }

Output:

What is the size of the square: 3
-4196312        1       0
3       -4196352        -13339222
4       -13360148       2

Solution

  • All variables in a function scope are not initialized to zero. Instead they are assigned to a random value.

    Use this:

    int square[size][size] = {0};
    

    You can also use memset or calloc, but this one is the simplest.


    Correction:

    The list initializer does not work with variable size array. Use memset instead:

    int square[size][size];
    memset(square, 0, size * size * sizeof(int));
    

    Edit:

    Entire working code

    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
        int size = 0;
        int r, c;
        int i = 1;
    
        printf("What is the size of the square: ");
        scanf("%d", &size);
    
        int square[size][size];
        memset(square, 0, size * size * sizeof(int));
        int range = size * size;
        r = 0;
        c = size/2;
    
        do {
            square[r][c] = i;
    
            i++;
            r--;
            c++;
    
            if ((r == -1) && (c == size)) {
                r = r + 2;
                c--;
            } else if (r == -1) {
                r = size - 1;
            } else if (c == size) {
                c = 0;
            } else if (square[r][c] != 0) {
                r = r + 2;
                c--;
            }
        } while (i < range);
    
        for (r = 0; r < size; r++) {
            for (c = 0; c < size; c++) {
                printf("%d \t", square[r][c]);
            }
            printf("\n");
        }
    
        return 0;
    }