繁体   English   中英

如何通过指针迭代二维数组?

[英]How can I iterate a 2 dimensional array via pointers?

我有一个 20x20 矩阵。 我想从矩阵中提取大量数据。 我有

int theMatrix[20][20] = {};//Full code initializes with #'s
int *theMatrixPointer = &theMatrix;

但后来我得到一个编译器警告说

警告:从不兼容的指针类型初始化

我继续运行代码,它看起来正在从左到右穿过矩阵。 至少在短期内。 实施:

//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
    }
}

在这里查看我对类似问题的回答。 基本上,我认为处理 theMatrix[20*20] 是比处理 theMatrix[20][20] 更明智的默认方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM