首页 > 解决方案 > 尝试在C中更改二维数组中的元素

问题描述

我想在函数 make2Darray 中实现,使二维数组中的元素与行号相对应。

打印和释放代码的其他部分已经给出,因此无需担心。我只是想触摸 make2Darray 函数。但是,在那个函数中,也给出了分配部分。因此,我要更改的唯一代码是更改 2D 数组中元素的部分。

int** make2Darray(int width, int height) {
  int **a;
  int i = 0;
  int j = 0;

  /*allocate memory to store pointers for each row*/
  a = (int **)calloc(height, sizeof(int *));
  if(a != NULL) {
    /* allocate memory to store data for each row*/
    for(i = 0; i < height; i++) {
      a[i] = (int *)calloc(width, sizeof(int));
      if(a[i] == NULL) {
        /* clean up */
        free2Darray(a, height);
        return NULL; /*aborting here*/
      }
    }
  }
    /* from this point down is the part I implemented, all code above was 
    given*/
    if (height < 0 && width < 0) {
      for (i = 0; i < height; i++) {
        for (j = 0; j < width; j++) {
          a[i][j] = j;
        }
      }
    }
    return a;
}

假设二维数组中的元素对应于行号 If height = 4 and width = 3

0  0  0
1  1  1
2  2  2
3  3  3

但是,我总是得到 0,这是我获得代码时的默认设置

0  0  0
0  0  0
0  0  0
0  0  0

标签: carraysmultidimensional-array

解决方案


您在代码中有两个主要问题。

1) 初始化二维数组的代码应if 块内

2)if (height < 0 && width < 0) {是错误的 - 你想要>而不是<

尝试:

int** make2Darray(int width, int height) {
  int **a;
  int i = 0;
  int j = 0;

  /*allocate memory to store pointers for each row*/
  a = (int **)calloc(height, sizeof(int *));
  if(a != NULL) {
    /* allocate memory to store data for each row*/
    for(i = 0; i < height; i++) {
      a[i] = (int *)calloc(width, sizeof(int));
      if(a[i] == NULL) {
        /* clean up */
        free2Darray(a, height);
        return NULL; /*aborting here*/
      }
    }

    // Moved inside the if(a != NULL) {

    /* from this point down is the part I implemented, all code above was 
    given*/
    if (height > 0 && width > 0) {   // Corrected this part 
      for (i = 0; i < height; i++) {
        for (j = 0; j < width; j++) {
          a[i][j] = j;
        }
      }
    }

  }
  return a;
}

几点提示:

1)在函数开始时检查高度和宽度 - 例如:

if (height <= 0 || width <= 0) return NULL;

2)原型make2Darray(int width, int height)对我来说似乎落后,因为我们通常在列数之前提到行数。我更喜欢:make2Darray(int height, int width)。我什至更喜欢术语“行”而不是“高度”和“列”而不是“宽度”。

3)你当前的代码在里面做“所有真实的东西”if(a != NULL) {没关系,但如果你这样做,代码(对我来说)会更清楚if(a == NULL) return NULL;

4) 无需投射calloc

通过这些更新,代码可能是:

int** make2Darray(int rows, int columns) {
  int **a;
  int i = 0;
  int j = 0;

  if (rows <= 0 || columns <= 0) return NULL;
  a = calloc(rows, sizeof(int*));
  if(a == NULL) return NULL;

  /* allocate memory to store data for each row*/
  for(i = 0; i < rows; i++) {
      a[i] = calloc(columns, sizeof(int));
      if(a[i] == NULL) {
        /* clean up */
        free2Darray(a, rows);
        return NULL; /*aborting here*/
      }
  }

  /* from this point down is the part I implemented, all code above was 
     given*/
  for (i = 0; i < rows; i++) {
      for (j = 0; j < columns; j++) {
          a[i][j] = j;
      }
  }

  return a;
}

推荐阅读