Search code examples
cstructuredynamic-memory-allocation

Using a creating structure function inside another function closes the program. Any tips?


This code was supposed to work with 2D matrices as they were one single array. I have to transpose the input matrix. The code for transposing and printing and reading values are all okay, but I can't create a new matrix using the function to put the transposed values there. Here's the code:

#include<stdio.h>
#include<stdlib.h>

struct Matriz {
int *p;
int lin, col, N;
};
typedef struct Matriz Matriz;

Matriz* CriaMatriz (int nlinhas, int ncolunas){
int tam=(nlinhas)*(ncolunas);
Matriz *a;
(*a).p=malloc(tam*sizeof(int));
(*a).col=ncolunas;
(*a).lin=nlinhas;
(*a).N=tam;
return a;
}

Matriz* TranspoeMatriz (Matriz *m){
int a=(*m).col;
int b=(*m).lin;

Matriz *t=CriaMatriz(a,b);  //THE PROBLEM HAPPENS HERE AND ALL THE PROGRAM SHUT DOWN

//some code

return t;   
}

int main(){
int o,p;
scanf("%d%d",&o,&p);

Matriz *g=CriaMatriz(o,p);
Matriz *tra=TranspoeMatriz(g);
}

I tried replacing the line where the problem occurs by this:

Matriz *t;
(*t).p=malloc((a*b)*sizeof(int));
(*t).col=b;
(*t).lin=a;
(*t).N=a*b;

And all did well, but I MUST use the CriaMatriz funtion to create new Matriz structures. I used a lot of printf's to find where the program stops and I left out a bunch of functions that were printing the outputs of the code as well the functions with the scanf's.


Solution

  • You have to allocate the memory in order to create a Matrix entity:

    Matriz *a;
    a = (Matriz*) malloc(sizeof(Matriz));