我编写了一个程序,它生成一个2d数组,然后设置它的编号。我有问题的第二步是,当我想移动行和列时,我将面临一行nmatrix[i*c+j] = 0;中的一个问题。
错误是:error: incompatible types in assignment of 'int' to 'int [(((sizetype)(((ssizetype)(c + shiftc)) + -1)) + 1)]'
以下是代码:
void shiftMatrix(int *matrix, int r,int c ,int shiftr,int shiftc){
int nmatrix [r+shiftr][c+shiftc];
for(int i = 0; i< shiftr; i++)
{
for(int j = 0; j<shiftc;j++)
{
nmatrix[i*c+j] = 0;
}
}
for(int i = shiftr; i< r; i++)
{
for(int j = shiftc; j<c;j++)
{
nmatrix[i*c+j] = matrix[i*c+j];
}
}
}有什么帮助吗??提前感谢
发布于 2013-12-10 20:22:32
int nmatrix [r+shiftr][c+shiftc];首先,您正在使用一个具有非常量边界的数组,这是一个controversial特性。
此外,这里您声明的是一个二维数组nmatrix,但是您的另一个矩阵(matrix)是指向int的指针(或者是一个一维数组,如果您想这样看的话)。这是造成混乱的药方。
您可以很容易地声明nmatrix (“新矩阵”?)作为一维数组:
int nmatrix[(r+shiftr) * (c+shiftc)];或者(大概更好)
std::vector<int> nmatrix((r+shiftr) * (c+shiftc));然后,您的代码nmatrix[i*c+j] = 0将工作(但是,无论何时使用nmatrix,您都必须将c更改为c+shiftc )。
发布于 2013-12-10 19:39:17
不能像处理数组那样动态地定义数组。您需要使用c++关键字new
int nmatrix[][] = new int [r+shiftr][c+shiftc];不能使用维度的非常量int值来定义数组,因为这种静态数组将在编译阶段为内存定义。因此,维度应该是const表达式。
与关键字new相反,您可以在运行时为数组定义维度,因为它是动态分配的。
在这个问题中有更详细的答案,所以问题here。
https://stackoverflow.com/questions/20503586
复制相似问题