I am having some troubles with implementing a dynamic matrix. Theoretically it seems clear what I have to do, and I have already read some similar question on this website (as well as on other resources). Although, the following very simple code doesn't work. Do you mind suggesting how to find the mistakes?
#include <stdio.h>
#include <stdlib.h>
int main() {
int dim1 = 10; // #Rows
int dim2 = 4; // #Columns
int i;
int j;
double **mtrx = (double **)malloc(sizeof(double **) * dim1);
// mtrx is my dynamic matrix, of size dim1*dim2 //
for (i = 0; i < dim1; ++i)
mtrx[i]= (double *)malloc(sizeof(double *) * dim2);
// (1) Inizialize//
for (i = 0; i < dim1; ++i) {
printf("(%d):\t", i);
for (j = 0; j < dim2; ++j) {
mtrx[i][j] = i;
printf("mtrx[%d][%d] = %.f ", i, j, mtrx[i][j]);
}
printf("\n");
}
// (2) Show the results//
printf("\nShow the results:\n");
for (i = 0; i < dim1; ++i) {
printf("(%d):\t", i);
for (j = 0; j < dim2; ++j)
printf("mtrx[%d][%d] = %.f ", i, j, mtrx[i][j]);
printf("\n");
}
// (3) Free the memory
printf("\n***free the memory***\n");
for (i = 0; i < dim1; ++i )
free(mtrx[i]);
free(mtrx);
return 0;
}
The purpose of my code is the following. First, declare a dynamic matrix of size dim1*dim2 (i.e. "dim1" rows and "dim2" columns). Than, phase (1), initialize every element following a simple pattern (mtrx[i][j] = i). Notice that here there is an "exceeding" printf instructions: I added it for "debugging" purposes, in oder to make sure of the correctness of the initialization procedure (that seems works correctly). Then, phase 2, I show the results, and finally I free the memory used.
The problems are:
- phase 2 doesn't show the results "correctly";
- at the free phase, I obtain an error like
***free (): invalid next size (fast) ...
My suspect: I may have wrongly declared the memory for my matrix, causing some overflow of data and an incompatibility with the "free" instruction, but unfortunately I don't manage to find the mistake.
I thank you in advance for any help!!!