开发者

How can I iterate a 2 dimensional array via pointers?

开发者 https://www.devze.com 2023-03-01 15:30 出处:网络
I have a 20x20 matrix.I want to extract chunks of data from the matrix.I have int theMatrix[20][20] = {};//Full code initializes with #\'s

I have a 20x20 matrix. 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 *. 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. But remember that theMatrixPointer is an address. This won't be 0 until you've iterated over the entire address space and wrapped back round!

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].

0

精彩评论

暂无评论...
验证码 换一张
取 消