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.