How to work on a sub-matrix in a matrix by pointer?

前端 未结 3 649
庸人自扰
庸人自扰 2020-11-28 14:19

I have a matrix of size n. Take an example:

My recursive function does the processing on the elements that lie in the border of the matrix. Now I want to c

3条回答
  •  执念已碎
    2020-11-28 14:33

    I am not sure of your application, but I wonder if using #define for your matrix size would help....

    #define X_SIZE 4
    #define Y_SIZE 4
    

    or even

    #define N_SIZE 4
    

    ... because then you can use X_SIZE and Y_SIZE (OR N_SIZE) in your function without having to pass them explicitly.

    in main you might put

     int matrix[X_SIZE * Y_SIZE];
    

    or

    int matrix2[N_SIZE * N_SIZE];
    

    then you can call the ith row and jth column element with

    *(pmatrix + X_SIZE*j + i) 
    

    or

    matrix[X_SIZE*j + i] 
    

    or

    *(pmatrix2 + N_SIZE*j + i)
    

    or

    matrix2[N_SIZE*j + i]
    

    where pmatrix and pmatrix2 are pointers to matrix and matrix2.

    I am pretty sure there is no clever trick to be able to easily pass the inner square 2x2 matrix to a function, unless you were to copy the elements from the centre of your matrix into a new matrix and then copy back the result afterwards.

提交回复
热议问题