指向矩阵的指针在 c++ 中引发异常

Pointer to a Matrix is throwing exception in c++

本文关键字:c++ 异常 指针      更新时间:2023-10-16

可能的重复项:
如何在 C 中使用动态多维数组?
静态矩阵强制转换为指针

我的此代码在行抛出异常

           resMat[i][j] = matp[i][j];

代码从这里开始

    #include <iostream>
    #define MOD 1000000007
    #define LL long long
    using namespace std;
    int mat[6][64][64],mat2[2][2], mat4[4][4], mat8[8][8], mat16[16][16], mat32[32][32], mat64[64][64];
    int **point[6];
    int resMat[64][64];
    void fooMatrix(int **matp, int size)
    {
        int i,j;
        // find canFollow of all matrixes   
        for(i=0;i<size;++i)
        {
            for(j=0;j<size;++j)
            {
      // throwing exception here
                resMat[i][j] = matp[i][j];
            }
        }
    }

    int main()
    {
        point[0] = (int **)mat2;
        point[1] = (int **)mat4;
        point[2] = (int **)mat8;
        point[3] = (int **)mat16;
        point[4] = (int **)mat32;
        point[5] = (int **)mat64;
        LL a,b,res;
        scanf("%lld %lld",&a,&b);
        fooMatrix(point[a-1],1<<a);
                    return 0;
    }

我想在我的函数 fooMatrix 中处理不同大小的 int 矩阵,比如说将其存储在 resMat 中。帮我解决这个问题。

我在Windows中使用DevC ++(g ++编译器)。

从上面的评论和链接中,我了解到这一点:

矩阵重复 [][] 和指针表示 ** 是不同的。编译器给了我警告。

2D 矩阵不是指针数组。 所以看看下面的代码

    #include <stdio.h>
#define MOD 1000000007
#define LL long long
int mat[6][64][64],mat2[2][2], mat4[4][4], mat8[8][8], mat16[16][16], mat32[32][32], mat64[64][64];
// see this is array of single pointer
int *point[6];
int resMat[64][64];
void fooMatrix(int *matp, int size)
{
    int i,j;
    // find canFollow of all matrixes   
    for(i=0;i<size;++i)
    {
        for(j=0;j<size;++j)
        {
               // this is how we would access the matrix.
            resMat[i][j] = matp[i*size+j];
        }
    }
}
int main()
{
    point[0] = &mat2[0][0];
    point[1] = &mat4[0][0];
    point[2] = &mat8[0][0];
    point[3] = &mat16[0][0];
    point[4] = &mat32[0][0];
    point[5] = &mat64[0][0];
    LL a,b,res;
    scanf("%lld %lld",&a,&b);
    fooMatrix(point[a-1],1<<a);
    return 0;
}

您不必使用矩阵,而是必须使用动态分配的指向数组的指针数组。

您可以将文件顶部的声明替换为以下内容:

int** newMat(int a, int b){
  int** result = new int*[a];
  for(int i=0; i<a; ++i)
    result[i] = new int[b];
  return result;
}
int** mat2 = newMat(2,2);
int** mat4 = newMat(4,4);
int** mat8 = newMat(8,8);
int** mat16 = newMat(16,16);
int** mat32 = newMat(32,32);
int** mat64 = newMat(64,64);
int*** point = new int**[6];
int** resMat= newMat(64,64);

然后将main顶部的作业更改为:

  point[0] = mat2;
  point[1] = mat4;
  point[2] = mat8;
  point[3] = mat16;
  point[4] = mat32;
  point[5] = mat64;