【问题标题】:How can I iterate a 2 dimensional array via pointers?如何通过指针迭代二维数组?
【发布时间】:2011-08-15 00:55:00
【问题描述】:

我有一个 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;
}

...随着时间的推移而中断,因为数据是垃圾(不在矩阵中的大整数)。那么,如何正确地用指针迭代这个矩阵呢?

【问题讨论】:

    标签: c pointers matrix


    【解决方案1】:

    首先,您收到警告的原因是因为&amp;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
        }
    }
    

    【讨论】:

    • i,j 索引迭代路线的问题是我计划的算法不起作用。我需要一次从矩阵 4 中提取块。每次拉动后,下一个索引需要通过冲洗重复上升一个。在一个类似但不同的问题上,我用一个字符串和指针干净地解决了这个问题,但这个矩阵被证明更具挑战性。我可能需要重新考虑我的方法。
    • @ssegvic 谢谢大家,我现在知道用指针来做这件事了。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 2010-09-25
      • 2013-05-19
      • 2018-04-17
      相关资源
      最近更新 更多