0

I am trying to print all the values in a two dimensional array. I come from Java and I'm having issues figuring this out in C. How do you access the value at two given indices in C?

void PrintArrayByPointer(int *ptrToArray)
{
    int i,j;

    printf("\nPrint Array By Pointers: \n");
    for(i=0; i<ROWS; i++)
    {
        for(j=0; j<COLS; j++)
        {
            // print the value here
        }
        printf("\n");
    }

    return;
}
5
  • @JohnnyMopp I believe it should be i*COLS+j Commented Apr 20, 2014 at 3:05
  • It depends on how you store the two dimensional data in a one dimensional array such as ptrToArray. Commented Apr 20, 2014 at 3:06
  • Assuming array data type double and ROWS & COLS are declared global ......... printf("%f",&ptrToArray[i*ROWS + j]) inside j-loop. Commented Apr 20, 2014 at 3:06
  • @Dukeling: that would be true if ptrToArray were an array of pointers to arrays, but the OP said it's a single 2D array, so because it degrades to a pointer upon passing to a function, you cannot expect ptrToArray[i][j] to work, because there is no way to know the length of each row. Commented Apr 20, 2014 at 3:07
  • Can you show where you set up the data you pass to this function? As shown, ptrToArray points to a 1-D array. Commented Apr 20, 2014 at 5:04

2 Answers 2

2
printf("%d ", ptrToArray[i*COLS + j]);

I assume here that your array is stored in row-major order, which is pretty typical in C and C++.

Sign up to request clarification or add additional context in comments.

Comments

1

It is a better way to change declaration to next one:

void PrintArrayByPointer(int **ptrToArray)

and you can access to array like this:

printf("Value[%d][%d]=%d", i, j, ptrToArray[i][j]);

In your case you should calculate position of your element in array like this:

printf("Value[%d][%d]=%d", i, j, ptrToArray[i*COLS+j]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.