c - 从 C 中的函数返回后变量值发生变化

标签 c variables matrix

我一直在为我的大学编写代码,在那里我们使用矩阵,但我无法在更改我保存矩阵列的变量值的代码中找到错误。我试过调试它但找不到它,它只是结束了我为矩阵分配内存的函数,并使用错误的列值进入下一个函数(从键盘获取值以填充矩阵)。 代码如下:

#include <stdio.h>
#include <stdlib.h>
#define DEBUG 1

void allocate (int ***mat,int n,int m){
    int i;
    *mat = (int **) malloc (n*sizeof(int*));
    for (i=0; i<n; i++){
        mat[i] = (int *) malloc (m*sizeof(int));
    }
    #if DEBUG
        printf ("allocate n: %d m: %d\n",n,m);
    #endif // DEBUG
}

void initialize (int **mat, int n, int m){
    int i,j;
    #if DEBUG
        printf ("initialize n: %d m: %d\n",n,m);
    #endif // DEBUG
    for (i=0; i<n; i++){
        for (j=0; j<m; j++){
            printf ("Enter value for position [%d][%d]: ",i,j);
            scanf ("%d",&(mat[i][j]));
        }
    }
}

int main()
{
        int n=2;
        int m=3;
        int **mat=NULL;
        #if DEBUG
            printf ("before allocate n: %d m: %d\n",n,m);
        #endif // DEBUG
        allocate (&mat,n,m);
         #if DEBUG
            printf ("after allocate n: %d m: %d\n",n,m);
        #endif // DEBUG
        initialize (mat,n,m);
        return 0;
}

因此,如果您在 DEBUG 设置为 1 的情况下运行此程序,您将获得 n 和 m 的值(它们是我的行和列)。我正在使用代码块。 感谢您的宝贵时间!

最佳答案

更新函数

void allocate( int ***mat, int n, int m )
{
    int i;

    *mat = (int **) malloc( n * sizeof( int* ) );
    for ( i = 0; i < n; i++ )
    {
        ( *mat )[i] = ( int *) malloc ( m * sizeof( int ) );
    }
    #if DEBUG
        printf ("allocate n: %d m: %d\n",n,m);
    #endif // DEBUG
}

关于c - 从 C 中的函数返回后变量值发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30926793/

相关文章:

c++ - 为什么切换/Case 而不是 If/Else If?

c - C 中的宏定义错误?

Java:变量持有者及其值(value)?

python - 矩阵数组的逐元素有效乘法

c - 有没有一种方法可以在将 int 的值实现到数组中之前扫描它?

c - 如何检查进程是否是我的后代(内核模式)

c - 简单的程序段错误

perl - Perl 脚本中子程序引用的分配

php - PHP 中函数 undefined variable

c - 如何在 C 中将数组转换为二维矩阵而不分配额外的内存?