0

我正在尝试编写一个 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
4

1 回答 1

2

函数范围内的所有变量都未初始化为零。相反,它们被分配给一个随机值。

用这个:

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

您也可以使用memsetor calloc,但这是最简单的。


更正:

列表初始值设定项不适用于可变大小数组。改用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;
}
于 2012-11-04T05:30:10.850 回答