How to print a 2D array in C without using the [] operator?

I'm trying to print a 2D-matrix by using [], instead I want to use *as a pointer.
So, with a 1 D array, I would do: *(arr+i)for example. What syntax is used to replace in matrix[][]?

Here is the code:

for (i = 0; i < size; i++)
{
    for (j = 0; j < (size * 2); j++)
    {
        printf(" %5d", matrix[i][j]);
    }
    printf("\n");
}

PS, I tried several things like:

*(matrix+i+j);
*(matrix+i)+*(matrix+j);

Of course, none of this worked.

Thanks for the help and time!

+4
source share
3 answers

This may depend on how the matrixfunction was allocated or passed.

int A[10][15];

It uses a continuous block of memory. To access elements without using array notation, use:

        A +(i*15)+j    // user694733 showed this is wrong
((int *)A)+(i*15)+j    // this is horribly ugly but is correct

15, 15 . .

:

int *A[10];

A - 10 int. , malloc, :

*(A+i) + j;

A, i - , j .

- EDIT -

:

int foo(int *p)

int. , n- . , .

n- , , .

int foo3(int *m, int dim2, int dim3, int i,  int j, int k)
{
    int *cell = m + i*dim3*dim2 + j*dim2 + k;
    return *cell;
}
0

* . * []:

*(*(matrix+i)+j)
+5

You can try this -

*(*(matrix+i)+j)  //reduce level of indirection by using *  
+2
source

Source: https://habr.com/ru/post/1628101/


All Articles