c - 将矩阵传递给函数后出现段错误

标签 c square

我的程序需要检查输入矩阵是否为 magic square .

快完成了,但是我的功能有问题。我不确定为什么,但它返回错误的值。我需要一个函数来返回 1 如果 square 是神奇的并且返回 0 如果 square 不是神奇的。我收到奇怪的输出和段错误。

输入示例:

3 - size of square, square: 
8 1 6
3 5 7
4 9 2

输出示例 (函数返回 1,因为方 block 很神奇) 打印在屏幕上的是 Square is magic。

代码:

#include<stdio.h>
#include <stdlib.h>

int is_magic(int m[][size], size_t size)
{
    int sum = 0;

    for(size_t col = 0; col < size; col++)
    {
        sum += m[col];
    }

    for(size_t row = 1; row < size; row++)
    {
        int psum = 0;
        for(size_t col = 0; col < size; col++)
        {
            psum += m[col + row * size];
        }
        if(psum != sum) return 0;
    }

    for(size_t col = 0; col < size; col++)
    {
        int psum = 0;
        for(size_t row = 0; row < size; row++)
        {
            psum += m[col + row * size];
        }
        if(psum != sum) return 0;
    }
    return 1;
}


int main()
{
      int size,row,column;
      scanf("%d",&size);
      int *matrix
      matrix = (int**)malloc(size * sizeof(int*));
            for (row = 0; row < size; row++)
                  matrix[row] = (int*)malloc(size * sizeof(int));


      for (row = 0; row < size; row++)
             for (column = 0; column < size; column++)
                   scanf("%d ", &matrix[row][column]);


       if(is_magic(matrix, size))
      {
            printf("Magic square");
      }
      else
      {
            printf("Not magic square");
      }
    return 0;
}

最佳答案

问题出在 is_magic 函数的签名上。你需要传入一个二维数组给它;

int is_magic(int **matrix,int size);

在这里,您将一个指针传递给一个 int 指针。

你需要传递一个二维数组如下:

int is_magic(int matrix[][size], int size);

确保使用 C99 兼容的编译器。

请注意,您可能需要也可能不需要颠倒 is_magic 函数的参数顺序。

为了符合参数的函数调用顺序,您实际上需要像下面这样颠倒参数的顺序。

int is_magic(int size, int matrix[][size]);

关于c - 将矩阵传递给函数后出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53894912/

相关文章:

c - 指针是否支持 "array style indexing"?

c++ - 在 Eclipse 中构建 C/C++ 项目时出错 : undefined referenced functions

c++ - 如何通过其 HWND 句柄更改另一个进程中 TDateTimePicker 控件中当前选定的日期?

使用变量作为文件名创建 C 结构

android - 如何使用 Retrofit 2 处理空响应体?

c - 我如何用 avrdude 删除 EEPROM 以外的所有内容?

jsf - 使 p :imageCropper area a fixed square

android - Retrofit - @Body 参数不能与表单或多部分编码一起使用

c++ - 如何设置方边线api窗口