c - 信号 11 SIG 错误并传递 free 参数 1 使指针来自整数而不进行强制转换

标签 c

我正在编写一个程序来读取和存储 3D 数组,然后打印所有 2D 部分,我收到此警告(对于 free(*mat1)[i][j]):

|warning: passing argument 1 of 'free' makes pointer from integer without a cast|

当我在计算机中运行该程序时,该程序运行得很好,但是当我在系统中提交它时,我收到如下错误: 错误类型:SIG

Message: Program was stopped by signal 11 [0.000000 sec]. Either Memory limit of 4000 Kb exceeded or invalid memory operation.

这是我的完整代码:

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


int main()
{
    int m,n,p,i,j,k;
    int *** mat1;
    scanf("%d",&m);
    scanf("%d",&n);
    scanf("%d",&p);

    mat1 =(int ***) malloc(m * sizeof(int **)); 
    if (mat1 == NULL)
    {
        printf("Error 1");
        exit(1);
    }
    for(i = 0; i < m; i++)
    {
        mat1[i] =(int **) malloc(n * sizeof(int *));
        if (mat1[i] == NULL)
        {
            printf("Error 2");
            exit(1);
        }
        for (j=0 ; j<n ; j++)
        {
            mat1[i][j] = (int * )malloc(p * sizeof(int ));
            if (mat1[i][j] == NULL)
            {
                printf("Error 3");
                exit(1);
            }

        }

    }


    for(i=0;i<m;i++) // reading matrix A input
    {
      for(j=0;j<n;j++)
      {
          for (k = 0 ; k < p ; k++)
          scanf("%d",&mat1[i][j][k]);
      }

    }

    for(i=0;i<p;i++) //output matrix A
    {
        printf("Section %d: \n", i+1);
        for(j=0;j<n;j++)
        {
            for (k = 0 ; k <m ; k++)
            {

                printf("%d ",mat1[k][j][i]);
            }
            printf("\n");
        }
    }


    for (i = 0; i < m; i++)
    {
        for (j = 0; j< n; j++)
        free((*mat1)[i][j]); //this row is where the warning is coming from
        free((*mat1)[i]);
    }
    free(*mat1);

    return 0;
}

最佳答案

这条线有效:

mat1[i][j] = (int * )malloc(p * sizeof(int ));

因为mat1是一个int***,所以mat1[i][j]是一个int*.

但这不是:

free((*mat1)[i][j]);

因为 *mat1 是一个 int**,所以 (*mat1)[i][j] 是一个 int,这正是提示中的警告。

我相信你想要的是:

free(mat1[i][j]);

对应于上面引用的malloc

关于c - 信号 11 SIG 错误并传递 free 参数 1 使指针来自整数而不进行强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48726135/

相关文章:

python - 如何包装带有 void* 指针的 C 函数?

将 mmap 的内存区域从 MAP_SHARED 更改为 MAP_PRIVATE

关于 C 中字符指针的困惑

c - 理解C编程语法

c - 使用 Excel C API (XLL)

正确或体面的 getopts_long 用法?

c - 未知转换类型字符

c - linux cp命令实现复制多个文件到一个目录

c - c 中的 scanf 和换行符

c中串口传输时字符\r转化为\n