【问题标题】:Variable value changing after returning from a function in C从C中的函数返回后变量值发生变化
【发布时间】:2015-06-18 22:20:00
【问题描述】:

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

#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 的值(这是我的行和列)。我正在使用代码块。 感谢您的宝贵时间!

【问题讨论】:

  • 你能提供一个示例输出吗?
  • 发布实际编译的代码。也修复警告。
  • 您需要将分配更改为(*mat)[i] = (int *) malloc (m*sizeof(int));
  • @ooga:是的,他有。但这不会导致他正在谈论的问题,因为那根本无法编译。
  • 编译后(修复分配,函数调用中的拼写错误initialize 和缺少分号),代码对我有用,我看不出有任何原因t.

标签: c variables matrix


【解决方案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
}

【讨论】:

    【解决方案2】:

    http://coliru.stacked-crooked.com/a/4d3cb5ed16ae73a5

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

    您看,您实际上并没有使用mat[i] 引用数组中的特定单元格。不,您实际上引用了指向矩阵的指针,然后索引到列或行,这意味着您为int* 分配了内存,而不是int

    因此,您需要将原始矩阵指针指向矩阵,然后索引 -> (mat*)[i]

    【讨论】:

      猜你喜欢
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 2013-11-20
      • 1970-01-01
      相关资源
      最近更新 更多