c++ - 如何使用指针到指针来传递矩阵?

标签 c++ c pointers matrix

将矩阵作为指针传递给函数指针不起作用。

#include <stdio.h>

void printMatrix(int **matrix, int row, int col)
{
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
            printf("%d ", matrix[i][j]);
        printf("\r\n");
    }
}
void printM (size_t row, size_t col, int matrix[3][4])
{
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
            printf("%d ", matrix[i][j]);
        printf("\r\n");
    }
}
int main() 
{
    int M[3][4];
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 4; j++)
            M[i][j] = 4*i+j;

    printM(3, 4, M);

    int *row = *M;
    printMatrix(&row, 3, 4);    //not working
}

函数printM可以工作,但我想知道如何正确使用指针到指针,感谢帮助。

最佳答案

首先感谢您提出这个问题。这是对 C 如何处理多维数组的很好的回顾。另外,使用双指针也是可以的。请记住,数组引用相当于指针,例如:a[0]*a 都引用 int a[12] 的第一个元素; 其中*a 是指针a 的取消引用。因此,当 M 声明为 int M[3][4];

&M 是指针 M 的地址>

为了清楚起见,我通过添加一些注释来修改您的代码,以便它可以使用 Microsoft 的 C 编译器在 Eclipse 中运行,特别是 int 声明已从 for 语句中移出。除此之外,它与您最初编写的内容相同,只是更改了 printMatrix 声明及其调用方式。

希望这对您有帮助,如有更多问题请询问...

    #include <stdio.h>

    void printMatrix(int (*matrix)[3][4], int row, int col)
    {
    int i, j;

    // point t so that when de-referenced it is at
    // the matrices first element
        int *t = (*matrix)[0];

    printf("\n");
        for (i = 0; i < row; i++)
        {
         // in C matrices are stored in Row Major form, so
         // per K&R just sequentially loop thru (*t)[12]
         for (j = 0; j < col; j++) {printf("%d ", *t++);}

         printf("\r\n");

        }
     } // end printMatrix

     void printM (size_t row, size_t col, int matrix[3][4])
     {
     int i, j;

     printf("\n");
         for (i = 0; i < row; i++)
         {
           for (j = 0; j < col; j++) {printf("%d ", matrix[i][j]);}

         // new line for next row
         printf("\r\n");
         }
      } 

    int main()
    {
      int i,j;

      // define a matrix with 3 rows and 4 columns
          int M[3][4];

          // fill-in the matrix with values
         for (i = 0; i < 3; i++)
           for (j = 0; j < 4; j++)
              M[i][j] = 4*i + j;

         // print the three rows and four columns of M
         printM(3, 4, M);

         printMatrix(&M, 3, 4);    // Also Works

     }  // end main

关于c++ - 如何使用指针到指针来传递矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17957186/

相关文章:

c++ - 插入USB时如何触发事件

c++ - 以下代码在 big endian 中的结果是什么?

c++ - OpenGL:标准化世界协调

c++ - 使用 std::vector 作为 header 中的输入参数定义函数的原型(prototype)

c - 为什么我在 C 语言中收到警告 'Segmentation fault, core dumped'

c - 程序崩溃

c - 如何正确释放与 getline() 函数相关的内存?

C++ 如何在内存中指定一个位置来获取数据?

c - typedef 结构混淆中的指针

c++ - 将 char * 转换为 vector C++