I’m currently working on a school (matrix multiplier) project and I have a problem.
I reprensent a matrix with a 2d array and I allocate it this way :
typedef struct matrix
{
int** matrix;
unsigned int l;
unsigned int c;
} matrix;
int matrix_alloc(matrix** matr, unsigned int l, unsigned int c)
{
unsigned int i, j;
*matr = malloc(sizeof(matrix)); /* Allocate memory for the structure */
if (*matr == NULL) /* Check if malloc succeeded */
{
fprintf(stderr, "malloc error"); /* If not print error */
return -1;
}
(*matr)->matrix = malloc(l*sizeof(int*)); /* Allocate memory for columns of the matrix*/
if ((*matr)->matrix == NULL)
{
fprintf(stderr, "malloc error");
free(*matr);
return -1;
}
for (i = 0; i < l; i++)
{
(*matr)->matrix[i] = malloc(c*sizeof(int));
if ((*matr)->matrix[i] == NULL)
{
fprintf(stderr, "malloc error");
for (j = 0; j < i; j++)
{
free((*matr)->matrix[j]);
}
free(*matr);
return -1;
}
for (j = 0; j < c; j++)
{
(*matr)->matrix[i][j] = 2; // Matrix should be filled with 2 for tests
printf("Element added : %d\n", (*matr)->matrix[i][j]);
}
}
(*matr)->l = l;
(*matr)->c = c;
printf("will print matrix----------------------\n");
matrix_print(*matr);
return 0;
}
And this is how I print the matrix
void matrix_print(matrix* m)
{
unsigned int i, j;
int v;
printf("********************************************************************************\n");
printf("Lines:\t %i\n", m->l);
printf("Cols:\t %i\n", m->c);
printf("Matrix::\n");
for (i = 0; i < m->l; i++)
{
for (j = 0; j < m->c; j++)
{
matrix_get_elem_at(v, i, j, m);
printf("\t%d", v);
/*printf("\t%ld", mpz_get_si(v)); */
}
printf("\n");
}
printf("********************************************************************************\n");
}
When I do
matrix* matr;
/* alloc matrix */
assert(matrix_alloc(&matr, 10, 10) == 0);
printf("----------------------------will print test matrix\n");
matrix_print(matr);
My matrix is filled with 32767 instead of 2
Can someone help me get rid of this bug?
Thank you
Ben
You should show us more code (for example, how did you declare
typedef matrix?) But I bet that the problem is inmatrix_get_elem_at– it should getint*for the first parameter. notint.