Reputation: 245
I have to use a static two-dimensional array and a dynamic matrix as a part of my college task. So, I've created them, and now trying to fill and then print them to a console, but getting "segmentation fault". That's how I'm trying to achieve it:
#include "arrayutils.h"
#include <stdlib.h>
#include <stdio.h>
#define ROWS 5
#define COLUMNS 7
int main3() {
/*init static array*/
double twodimarray[ROWS][COLUMNS];
/*init dynamic array*/
double **matrix = (double**) malloc(sizeof(double*) * ROWS);
for(int i = 0; i < ROWS; i++) *(matrix + i) = (double*)malloc(sizeof(double) * COLUMNS);
for(int i = 0; i < ROWS; i++){
dfillarran(*(matrix + i), COLUMNS);
dfillarran(twodimarray[i], COLUMNS);
}
puts("Dynamic matrix :");
printmx(matrix, ROWS,COLUMNS);
puts("Static array:");
printmx(twodimarray, ROWS, COLUMNS);
/*freeing mem*/
for(int i = 0; i < ROWS; i++) free(*(matrix + i));
free(matrix);
}
Error is definitely in function printmx()
, but I can't understand why; It works for dynamic matrix, and fails only for static one, but static array name - is a pointer to array of pointers, where each one is pointing array of values, just like dynamic one!
There is code of my printmx()
function from arrayutils.h
:
/**Print Matrix*/
void printmx(double** mx, int rows, int col){
for(int i = 0; i < rows; i++) {
for(int j = 0; j < col; j++){
printf("%.lf ", *(*(mx + i)+j));
}
putchar('\n');
}
putchar('\n');
}
Funcion that fills arrays with random values can be found here, in arrayutils.c
, that I've created for all other tasks that use same functions like filling and printing arrays, but I don't think, that problem is there..
Probably, I'm wrong somewhere in theory, and still not getting the difference between static and dynamic matrix, please correct me :)
p.s.There is a screenshot of the error:
Upvotes: 1
Views: 81
Reputation: 311038
The function printmx
may not be called for the two objects of different types.
The array twodimarray
is a two dimensional array that when is passed to the function has the type double ( * )[COLUMNS]
.
While matrix is a pointer of the type double **
.
Upvotes: 3