首页 > 解决方案 > 尝试调用单独的函数时未定义的行为

问题描述

该程序打印 anxn square,其中所有行、列和对角线的总和相同。我成功地编写了这段代码而没有调用单独的函数(create_magic_squareprint_magic_square这种情况下),但是使用单独的函数,编译器会返回一个随机数(-1073741571)。

#include <stdio.h>
void create_magic_square(int n, int magic_square[n][n]);
void print_magic_square (int n, int magic_square[n][n]);

int main(void) /*creates magic square, in which the sums of the rows, columns and diagonals are all the same */
{
    int n, magic_square[n][n];
    printf("Enter the number: "); /*n must be odd */
    scanf("%d", &n);
    create_magic_square(n, magic_square);
    print_magic_square(n, magic_square);
    return 0;
}
void create_magic_square(int n, int magic_square[n][n])
{
    int i, j, a, x, y;
    for (i = 0; i <= n-1; i++) {
        for (j = 0; j <= n-1; j++)
            magic_square[i][j] = 0; /*Initializes the n x n matrix */
    }
    i = 0; j = n/2;
    magic_square[i][j] = 1;  /*first put the number 1 in the middle of row 0 */
    for (a = 2; a <= n*n; a++) {
       if (i == 0)
        i = n;
       if (j == (n-1))
        j = -1;

       if (magic_square[i-1][j+1] == 0) { /*If the element up 1 row and over 1 column is not yet occupied */
        i = i - 1;
        j = j + 1;
        magic_square[i][j] = a; /*assigns a to this element */
       }

       else if (magic_square[i-1][j+1] != 0) { /*If the element up 1 row and over 1 column is already occupied*/
        i = x; /*Assigns i to its value in the previous loop */
        j = y; /*Assigns j to its value in the previous loop */
        if (i == (n-1))
            i = -1;
        i = i + 1;
        magic_square[i][j] = a; /*assigns a to the element directly below the previously stored number */
       }
       x = i; /*Stores the current i value */
       y = j; /*Stores the current j value */
    }
    for (i = 0; i <= n-1; i++) {
        for (j = 0; j <= n-1; j++)
            printf(" %3d ", magic_square[i][j]);
        printf("\n");
    }
}

void print_magic_square (int n, int magic_square[n][n]) /*prints the square*/
{
    int i, j;
    for (i = 0; i <= n-1; i++) {
        for (j = 0; j <= n-1; j++)
            printf(" %3d ", magic_square[i][j]);
        printf("\n");
    }
}

编译器没有检测到任何错误或产生任何警告,但它没有返回任何内容,即使是printf(输入数字)中的消息

标签: c

解决方案


正如@Jonathan Leffler 所说,当您使用它来定义数组时,n 未初始化。在 scanf 之后定义数组。这种方式将确定数组大小。

int main(void)
{
    int n;
    printf("Enter the number: "); /*n must be odd */
    if (scanf("%d", &n) != 1 || n % 2 != 1 || n > 25 || n < 3)
    {
        fprintf(stderr, "invalid size for magic square\n");
        return 1;
    }
    int magic_square[n][n];
    …

推荐阅读