Changing the value of a variable after returning from a function in C

I have been coding my university where we work with matrices and I cannot find an error in the code that changes the value of a variable where I store the columns of the matrix. I've tried debugging it and can't find it, it just ends up the function where I allocate memory from the matrix and injects the following function (which gets values ​​from the keyboard to populate the matrix) with the wrong column value. The following code:

#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;
}

      

So, if you run this with DEBUG set to 1, you get the values ​​n and m (which are my rows and columns). I am using code blocks. Thank you for your time!

+3


source to share


2 answers


Update function



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
}

      

+1


source


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
}

      



You can see that you were not actually referencing a specific cell in the array with mat[i]

. No, you were actually referencing a pointer to a matrix and then indexing into a column or row, which means you allocated memory for int*

, not int

.

So you need to read the original matrix pointer to matrix and then index -> (mat*)[i]

.

+1


source







All Articles