Question

I created a typedef matrix:

typedef struct matrix {
int m;  
int n;
int **vrednosti;
} matrix ;

and a function that creates a matrix:

matrix* create_matrix(int x, int y, int** val)

but when I set the dimensions (m and n)

mat.n = x;
mat.m = y;

only n gets actually set. When i print them out after setting them I get something like that

n = 3
m = -1717986919

even though I set n = 3 and m = 3.

Full code:

typedef struct matrix {
int m;  
int n;
int **vrednosti;
} matrix ;


matrix* create_matrix(int x, int y, int** val){
matrix mat;
mat.n = x;
mat.m = y;
mat.vrednosti = val;
matrix* trol = &mat;
return trol;
}


int main(int argc, char* argv[]){
int n = *argv[1]-'0';
int m = *argv[2]-'0';

int i,j;
int** tab;
tab = (int**)malloc(n*sizeof(int*));
for(i=0; i<n; i++){
    tab[i] = (int*)malloc(m*sizeof(int));   
}

for(i=0; i<n; i++){
    for(j=0; j<m; j++){
        scanf("%d",&tab[i][j]);
    }
}

matrix* mat;
mat = create_matrix(n,m,tab);
printf("%d ",(*mat).n);
printf("%d ",(*mat).m);4

return 0;

}

Was it helpful?

Solution

It is most likely that you create a matrix object local to the function and return its address. The object does not exist beyond the scope of the function and gives you undefined behavior. Your implementation probably looks something like:

matrix* create_matrix(int x, int y, int** val)
{
       matrix mat;
       mat.n = x;
       mat.m = y;

       return &mat;
}

There are a number of ways to solve the problem the basic of each of those rules is:

  • To increase the lifetime of the object(who's address is returned) even after the function exits.

The exact way depends on the functionality you want to achieve. Simplest being returning a object itself by value, or dynamically allocating the object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top