我有一个 20x20 矩阵。我想从矩阵中提取数据 block 。我有
int theMatrix[20][20] = {};//Full code initializes with #'s
int *theMatrixPointer = &theMatrix;
但随后我收到编译器警告:
warning: initialization from incompatible pointer type
我继续运行代码,它看起来从左到右穿过矩阵。至少在短期内是这样。实现:
//left to right with pointer;
while(theMatrixPointer)
{
int one = 0;
int two = 0;
int three = 0;
int four = 0;
double currentProduct = 0;
//int stop = 0;
for(int i = 0; i < depth; i++)
{
/*if(!theMatrixPointer)
{
stop = 1;
break;
}*/
int currentValue = *theMatrixPointer++;
printf("%d\n",currentValue);
if(i == 0)
{
one = currentValue;
}
else if (i == 1)
{
two = currentValue;
}
else if (i == 2)
{
three = currentValue;
}
else if (i == 3)
{
four = currentValue;
}
}
/*if(stop)
break;*/
currentProduct = one * (double)two * three * four;
printf("PRODUCT: %f\n",currentProduct);
startPoint++;
theMatrixPointer = startPoint;
}
...随着时间的推移会中断,因为数据是垃圾(不在矩阵中的大整数)。那么,如何用指针正确迭代这个矩阵呢?
最佳答案
首先,您收到警告的原因是 &theMatrix
的类型为 int(*)[20][20]
,而 theMatrixPointer
> 的类型为int *
。你想要这个:
int *theMatrixPointer = &theMatrix[0][0];
其次,您收到垃圾的原因是因为您超出了数组的末尾。 while (theMatrixPointer)
将迭代直到 theMatrixPointer == 0
。但请记住,theMatrixPointer
是一个地址。在您迭代整个地址空间并回绕之前,这不会是0
!
你最好这样做:
int i, j;
for (i = 0; i < 20; i++)
{
for (j = 0; j < 20; j++)
{
// matrixPointer[i][j] is the current element
}
}
关于c - 如何通过指针迭代二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5824567/