如何在由指针的矩阵的子矩阵工作? [英] How to work on a sub-matrix in a matrix by pointer?
问题描述
我有大小n矩阵。举一个例子:
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 call it (the recursive call) on the inner square matrix:
这是我的递归函数的原型:
This is the prototype of my recursive function:
void rotate(int** mat, size_t n);
我知道,一个二维数组是一个数组内的数组。我知道, *(垫+ 1)+ 1)
会给这应该是我的新基的基地址的内存地址。这是我尝试:
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)
但它不工作,我也得到段错误,当我尝试访问它 [] []
。
推荐答案
您不能解引用垫+ 1
和reinter preT,作为一个指向整个矩阵。而要提供偏移作为参数传递给你的函数(我假设 N
-by - N
方阵):
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
// ...
}
这篇关于如何在由指针的矩阵的子矩阵工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!