-1

I have a 2D array called matrix, now I would like to add one to every element.

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

However, the compiler told me that

[Error] cannot convert 'int (*)[2]' to 'int**' for argument '1' to 'int** add_one(int**, int, int)'

abc
  • 99
  • 3
  • http://ideone.com/UUL3c0 – BLUEPIXY Aug 29 '16 at 01:53
  • Note that with C99 and VLAs (variable length arrays), you could use: `int **add_one(int m, int n, int matrix[m][n]) {` and a number of variations on that theme — specifying the sizes before the array that uses those sizes. However, that's tangential to your problem, which has been accurately diagnosed. – Jonathan Leffler Aug 29 '16 at 03:20
  • @JonathanLeffler what would that function `return` exactly – M.M Aug 29 '16 at 03:44
  • @M.M: It would return what it returns now — an allocated array of pointers, each of which points to an allocated array of `int`. It's only the input that would be different, not the output. – Jonathan Leffler Aug 29 '16 at 03:47

1 Answers1

1

It works a bit differently from what you thought

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

If you want to pass the two-star matrix as a two-star matrix you need to build it like the new_mat in the function add_one.

deamentiaemundi
  • 5,502
  • 2
  • 12
  • 20