如何正确使用二级指针?

时间:2016-08-29 01:43:15

标签: c pointers

我有一个名为matrix的2D数组,现在我想为每个元素添加一个。

#include <stdio.h>
#include <stdlib.h>

int **add_one(int **matrix, int m, int n) {
    int i, j;
    int **new_mat;
    new_mat = (int **) malloc(m * n *sizeof(int));

    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            new_mat[i][j] = matrix[i][j] + 1;
        }
    }
    //return the 2nd rank pointer
    return new_mat;
}

int main() {
    int matrix[3][2] = {1, 2, 3, 4, 5, 6};
    int **new_mat;
    int i, j;
    new_mat = add_one(matrix, 3, 2);

    for (i = 0; i < 3; i++) {
        for (j = 0; j < 2; j++) {
            printf("%d  ", new_mat[i][j]);
        }
        printf("\n");
    }
    free(new_mat);
}

然而,编译器告诉我

  

[错误]无法转换&#39; int(*)[2]&#39;到&#39; int **&#39;争论&#39; 1&#39; to&#39; int ** add_one(int **,int,int)&#39;

1 个答案:

答案 0 :(得分:1)

它与您的想法有点不同

#include <stdio.h>
#include <stdlib.h>
// you can only pass what you have
int **add_one(int matrix[3][2], int m, int n)
{
  int i, j;
  int **new_mat;
  // allocate m pointers (the rows)
  new_mat = malloc(m * sizeof(*new_mat));

  for (i = 0; i < m; i++) {
    // allocate space for n ints
    new_mat[i] = malloc(n * sizeof(int));
    for (j = 0; j < n; j++) {
      new_mat[i][j] = matrix[i][j] + 1;
    }
  }
  //return the 2nd rank pointer
  return new_mat;
}

int main()
{
  // you forgot to encapsulate the rows, too
  int matrix[3][2] = { {1, 2}, {3, 4}, {5, 6} };
  int **new_mat;
  int i, j;
  new_mat = add_one(matrix, 3, 2);

  for (i = 0; i < 3; i++) {
    for (j = 0; j < 2; j++) {
      printf(" %d ", new_mat[i][j]);
    }
    printf("\n");
  }
  free(new_mat);
}

如果要将双星矩阵作为双星矩阵传递,则需要像函数new_mat中的add_one一样构建它。