如何通过指针处理矩阵中的子矩阵? [英] How to work on a sub-matrix in a matrix by pointer?

查看:22
本文介绍了如何通过指针处理矩阵中的子矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大小为 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);

我知道二维数组是数组中的数组.我知道 *(mat+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)

但它不起作用,当我尝试使用 [][] 访问它时出现段错误.

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

推荐答案

您不能取消引用 mat+1 并将其重新解释为指向整个矩阵的指针.而是提供偏移量作为函数的参数(我假设 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆