简体   繁体   English

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

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

I have a 20x20 matrix.我有一个 20x20 矩阵。 I want to extract chunks of data from the matrix.我想从矩阵中提取大量数据。 I have我有

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

But then I get a compiler warning saying但后来我得到一个编译器警告说

warning: initialization from incompatible pointer type警告:从不兼容的指针类型初始化

I went ahead and ran the code and it looks to be moving across the matrix from left to right.我继续运行代码,它看起来正在从左到右穿过矩阵。 At least in the short run.至少在短期内。 The implementation:实施:

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

...breaks over time as the data is garbage (big ints that are not in the matrix). ...随着时间的推移而中断,因为数据是垃圾(不在矩阵中的大整数)。 So, how can I properly iterate this matrix with a pointer?那么,我怎样才能正确地用指针迭代这个矩阵呢?

Firstly, the reason you get the warning is because &theMatrix is of type int(*)[20][20] , whereas theMatrixPointer is of type int * .首先,您收到警告的原因是&theMatrix的类型为int(*)[20][20] ,而theMatrixPointer的类型为int * You want this:你要这个:

int *theMatrixPointer = &theMatrix[0][0];

Secondly, the reason you are getting garbage is because you're going past the end of the array.其次,你得到垃圾的原因是因为你越过了数组的末尾。 while (theMatrixPointer) will iterate until theMatrixPointer == 0 . while (theMatrixPointer)将迭代直到theMatrixPointer == 0 But remember that theMatrixPointer is an address .但请记住, theMatrixPointer一个地址 This won't be 0 until you've iterated over the entire address space and wrapped back round!在您遍历整个地址空间并回绕之前,这不会是0

You are probably best off doing this:你可能最好这样做:

int i, j;
for (i = 0; i < 20; i++)
{
    for (j = 0; j < 20; j++)
    {
        // matrixPointer[i][j] is the current element
    }
}

Check my answer to a similar question here .在这里查看我对类似问题的回答。 Basically, I think that dealing with theMatrix[20*20] is a wiser default approach than dealing with theMatrix[20][20].基本上,我认为处理 theMatrix[20*20] 是比处理 theMatrix[20][20] 更明智的默认方法。

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

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