Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C programming initialize 2D array dynamically

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

like image 754
JDS Avatar asked Jul 26 '26 23:07

JDS


1 Answers

You are making a few mistakes in your pointers. You are passing the &dataA to init_data, so the argument type should be ***double, instead of **double. Also your first malloc is initializing an array of pointers, not an array of doubles, so it should be sizeof(double *) * dim_x. The code below should work.

void init_data(double ***data_ptr, int dim_x, int dim_y) {
  int i,j,k;
  double **data;
  data = (double **) malloc(sizeof(double *) * dim_x);
  for (k = 0; k < dim_x; 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);
      }
  }
  *data_ptr = data;
}

void main() {
  double **dataA;
  int dim = 10;
  init_data(&dataA, dim, dim);
  int i,j;
      for(i=0;i<dim;i++)
          for(j=0;j<dim;j++)
              printf("%f\n", dataA[i][j]);
}

Your first loop should also have the condition k < dim_x instead of k < 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 %f instead of %d in your printf, as doubles are stored in a different format than integers, and you are likely to get gibberish instead than what you want.

like image 157
Yunchi Avatar answered Jul 28 '26 15:07

Yunchi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!