Hi,
I have a really basic question about dynamic memory allocation. Is it necessary to free memory allocated to matrix temp (in function transpose) ?
Code:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct dMat {
int rows;
int cols;
double **t;
};
struct dMat allocate(int rows, int cols)
{
struct dMat t;
int i;
t.rows=rows;
t.cols=cols;
t.t=(double **)malloc(t.rows * sizeof(double *));
for(i = 0; i < t.rows; i++)
t.t[i] = (double *) malloc(cols * sizeof(double));
return t;
}
struct dMat transpose(struct dMat t)
{
struct dMat temp;
int i, j;
temp.cols = t.rows;
temp.rows = t.cols;
temp = allocate(temp.rows, temp.cols);
for(i=0; i<temp.rows; i++)
for(j=0; j<temp.cols; j++)
*(*(temp.t+i)+j)=*(*(t.t+j)+i);
return temp;
}
void display(struct dMat t){
int i,j;
for(i=0;i<t.rows;i++) {
for(j=0;j<t.cols;j++)
printf("%.3f ",*(*(t.t+i)+j));
printf("\n");
}
printf("\n");
printf("Dimension = [%d, %d]\n\n", t.rows, t.cols);
}
int main() {
struct dMat beta;
int i, j;
beta.rows = 5;
beta.cols = 6;
beta = allocate(beta.rows, beta.cols);
for(i = 0; i < beta.rows; i++)
for(j = 0; j < beta.cols; j++)
*(*(beta.t+i)+j) = 2.5*(i+j);
display(beta);
display(transpose(beta));
free(beta.t);
getch();
return 0;
}