Home > Software engineering >  Hard time understanding how to access the matrix inside the function and how it was passed into the
Hard time understanding how to access the matrix inside the function and how it was passed into the

Time:04-09

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

For a complete picture of the question: https://leetcode.com/problems/rotate-image/

The function where the matrix is passed:

void rotate(int** matrix, int matrixSize, int* matrixColSize);

Just to clarify, I'm not asking for how to solve the leetcode problem, what I'm asking for is 1) how did they make the matrix in main, 2) how was it passed into the function stated above 3) how to access the elements inside the function. I have a hard time grasping visually a pointer to a pointer.

CodePudding user response:

  1. matrix is of type pointer to pointer, the function can only take an argument of the same type, so you'd have to pass to it an array created by way of memory allocation, for example:

    int **matrix = malloc(rows * sizeof *matrix);
    
    for(int i = 0; i < rows; i  )
        matrix[i] = malloc(cols * sizeof **matrix);
    
  2. You pass it like you do any other variable, respecting the type:

    int main() {
    
        int **matrix = malloc(rows * sizeof *matrix);
    
        for(int i = 0; i < rows; i  )
            matrix[i] = malloc(cols * sizeof **matrix);
    
        rotate(matrix, ...);
    }
    
  3. The cleaner way you index it is the same as if it was a statically declared 2D array, i.e. int matrix[5][5].

    For example:

    void rotate(int** matrix, ...){   
    
        printf( "%d", matrix[0][0]);
    
    }
    

The above will, of course, access the element in the first row and first column like you'd expect.

For simplicity sake I did not check the return value of malloc, which you should.

The parameters are kind of confusing, but I guess it's a way of complicating the issue to make the problem more difficult. The normal way would be to pass the dimensions of the array, i.e.:

void rotate(int** matrix, int rows, int cols);

There is no point of having the third argument be a pointer, nor passing the whole size of the array by the way, it will lead to unnecessary logic.

More simple yet would be to avoid a third parameter altogether, since it is a square matrix.

  • Related