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

已经给出了打印和释放代码的其他部分,因此无需担心。我只想碰一下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;
}


假设2D数组中的元素对应于行号
如果高度= 4且宽度= 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

最佳答案

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

1)初始化2D数组的代码应在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;
}

关于c - 试图在C中更改2D数组中的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54475287/

10-10 06:34