打印2D阵列打印垃圾(魔术广场)

时间:2012-11-04 05:27:58

标签: c arrays magic-square

我正在尝试编写一个C程序来打印魔方。但是,我在构建广场时遇到错误。任何人都可以帮助找出造成这些错误的原因吗?以下是我的相关代码和我的输出:

代码:

  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;
  }

输出:

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

1 个答案:

答案 0 :(得分:2)

函数作用域中的所有变量都不会初始化为零。而是将它们分配给随机值。

使用此:

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

您也可以使用memsetcalloc,但这个是最简单的。


<强>校正:

列表初始值设定项不适用于可变大小的数组。请改用memset

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

编辑:

整个工作代码

#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;
}