I’m doing something silly here and I can’t put my finger on exactly what:
void init_data(double **data, int dim_x, int dim_y) {
int i,j,k;
data = (double **) malloc(sizeof(double) * dim_x);
for (k = 0; k < dim_y; k++) {
data[k] = (double *) malloc(sizeof(double) * dim_y);
}
for (i = 0; i < dim_x; i++) {
for (j = 0; j < dim_y; j++) {
data[i][j] = ((double)rand()/(double)RAND_MAX);
}
}
}
And in main() I do the following:
double **dataA;
int dim = 10;
init_data(&dataA, dim, dim);
But then right after that when I try printing the data the program crashes:
int i,j;
for(i=0;i<dim;i++)
for(j=0;j<dim;j++)
printf("%d\n", dataA[i][j]);
What am I missing?
Thanks
You are making a few mistakes in your pointers. You are passing the
&dataAtoinit_data, so the argument type should be***double, instead of**double. Also your firstmallocis initializing an array of pointers, not an array of doubles, so it should besizeof(double *) * dim_x. The code below should work.Your first loop should also have the condition
k < dim_xinstead ofk < dim_y. It doesn’t matter in the current case since both dimensions are the same, but would cause issues if they weren’t. Finally, you should use%finstead of%din yourprintf, as doubles are stored in a different format than integers, and you are likely to get gibberish instead than what you want.