Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

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

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

enter image description here

My recursive function does the processing on the elements that lie in the border of the matrix. Now I want to call it (the recursive call) on the inner square matrix:

enter image description here

This is the prototype of my recursive function:

void rotate(int** mat, size_t n);

I know that a 2D array is an array within an array. I know that *(mat+1) + 1) will give the memory address that should be the base address of my new matrix. This is what I tried:

rotate((int **)(*(mat+1) + 1), n-2)

But it does not work, and I get a segfault when I try to access it with [][].

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot dereference mat+1 and reinterpret that as a pointer to a whole matrix. Instead provide the offsets as arguments to your function (I assume n-by-n square matrices):

void rotate(int** mat, size_t i, size_t j, size_t n) {
    // assuming row-wise storage
    int *row0 = mat[j];     // assumes j < n
    int *row1 = mat[j + 1]; // assumes j + 1 < n
    // access row0[i..] and row1[i..]
}

If you had continuous storage for your matrix, you could do the following instead:

rotate(int* mat, size_t i, size_t j, size_t n) {
    int atIJ = mat[j * n + i]; // assuming row-wise storage
    // ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...