可能重复:
How do I work with dynamic multi-dimensional arrays in C?
Static Matrix Casting to a pointer
我的这段代码在行
处抛出异常 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 ++编译器)。
答案 0 :(得分:1)
从上面的评论和链接中读到我了解到这一点:
矩阵represntation [] []和指针表示**是不同的。编译器给了我警告。
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;
}
答案 1 :(得分: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;