I am learning C. I have a program that dynamically creates and fills two matrices X and Y, with random numbers using rand() as shown below
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main(){
int i, j, k, m, n;
double **x;
double **y;
printf("Enter a number as the size of two square matrices\n");
scanf("%d", &m);
x = (double**)malloc(m * sizeof(double));
y = (double**)malloc(m * sizeof(double));
/* initialize random seed: */
srand(time(NULL));
for(i = 0; i < m; i++) {
x[i] = (double*)malloc(m * sizeof(double));
y[i] = (double*)malloc(m * sizeof(double));
for(i = 0; i < m; i++) {
for(j = 0; j < m; j++) {
x[i][j] = rand();
y[i][j] = rand();
}
printf("\n");
}
}
printf("\n\n");
}
When I run this program and give 2 as size of my matrix, I am seeing "Segmetation Fault" as error. Please note that the idea is to fill the two matrices with random elements of type double. Let me know if the above code is correct.
Corrected:Edit1
x = (double**)malloc(m * sizeof(double*));
y = (double**)malloc(m * sizeof(double*));
/* initialize random seed: */
srand(time(NULL));
for(i = 0; i < m; i++) {
x[i] = (double*)malloc(m * sizeof(double));
y[i] = (double*)malloc(m * sizeof(double));
for(j = 0; j < m; j++) {
x[i][j] = rand();
y[i][j] = rand();
}
printf("\n");
}
printf("\n\n");
}
Above is working correctly now. Need some explanation on x = (double**)malloc(m * sizeof(double*)); and x[i] = (double*)malloc(m * sizeof(double));
why * for sizeof(double*) in x = (double**)malloc(m * sizeof(double*));
Edit2
void main(){
int i, j, k, m, n;
printf("Enter a number as the size of two square matrices\n");
scanf("%d", &m);
double (*x)[m] = malloc(sizeof(double[m][m]));
double (*y)[m] = malloc(sizeof(double[m][m]));
/* initialize random seed: */
srand(time(NULL));
for(i = 0; i < m; i++) {
for(j = 0; j < m; j++) {
x[i][j] = rand();
y[i][j] = rand();
}
printf("\n");
}
printf("\n\n");
}
As per Jens Gustedt matrix allocation changed... I have removed
double **x;
double **y;
x = (double**)malloc(m * sizeof(double*));
y = (double**)malloc(m * sizeof(double*));
x[i] = (double*)malloc(m * sizeof(double));
y[i] = (double*)malloc(m * sizeof(double));
double (*matrix)[m] = malloc(sizeof(double[m][m]));. So you only need one call tomallocfor the whole matrix and have it all in consecutive memory. - Jens Gustedt