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

标签 c pointers matrix

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

相关文章:

matlab - 在 MATLAB 中使用 if 语句组合另外两个矩阵来创建新矩阵

连接宏名称

c - 理解 argv 和 *++argv[0]

c - 指向地址 C 的字符串

OpenCV 垫类 : Accessing elements of a multi-channel matrix

r - 通过对另一个矩阵的行求和在 R 中创建新矩阵

c++ - C 枚举在 C++ 中无法识别

c - 基于先前值的 X-macro 枚举

C - 两个指针之间的距离

c++ - "if(pointer) delete ponter"即使指针未初始化也尝试删除