C编程动态初始化2D数组 [英] C programming initialize 2D array dynamically

查看:83
本文介绍了C编程动态初始化2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里做些愚蠢的事情,我不能完全指责什么:

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);
        }
    }
}

然后在main()中执行以下操作:

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]);

我想念什么?

谢谢

推荐答案

您在指针中犯了一些错误.您要将& dataA传递给init_data,因此参数类型应为*** double,而不是** double.同样,您的第一个malloc正在初始化一个指针数组,而不是一个double数组,因此它应该是sizeof(double *)* dim_x.下面的代码应该可以工作.

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]);
}

您的第一个循环还应具有条件k< dim_x而不是k< dim_y.在当前情况下这并不重要,因为这两个维度相同,但是如果两个维度都不相同,则会引起问题.最后,您应该在printf中使用%f而不是%d,因为双精度数以与整数不同的格式存储,并且很可能出现乱码而不是您想要的东西.

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.

这篇关于C编程动态初始化2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆