c - 尝试调用单独的函数时未定义的行为
问题描述
该程序打印 anxn square,其中所有行、列和对角线的总和相同。我成功地编写了这段代码而没有调用单独的函数(create_magic_square
在print_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
(输入数字)中的消息
解决方案
正如@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];
…
推荐阅读
- angular - 命名路由器出口匹配但保持为空
- python - 基于另一个列值查找最小值并合并到 1 个数据帧中的循环?
- javascript - 根据下拉值显示匹配的嵌套子 div
- amazon-redshift - 需要 SQL 调试帮助
- python - csv文件中的所有内容都转换为int64?
- ios - 如何将数据添加到 Firestore 数据库中的特定 uid?
- python-3.x - 从 4 个不同角度融合图像
- sql - 在 Postgres 中将数据从一个表传输到另一个表,两个表具有相同的 id
- python - 您可以在特定行之后删除 .txt 文件的所有行吗?
- excel-formula - 如何将不同列中的值放入Excel中的一列?