问题
I am trying to print a 2D matrix with using []
, instead I want to use *
like a pointer.
So with a 1 D array I'd do: *(arr+i)
for example.
What's the syntax used to replace in matrix[][]
?
Here's the code:
for (i = 0; i < size; i++)
{
for (j = 0; j < (size * 2); j++)
{
printf(" %5d", matrix[i][j]);
}
printf("\n");
}
P.S, I did try several things like:
*(matrix+i+j);
*(matrix+i)+*(matrix+j);
Of course none of that worked.
Thank you for your help and time!
回答1:
This may depend on how matrix
was allocated or passed to a function.
int A[10][15];
This uses a contiguous block of memory. To address the 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
Note the 15, as each row consists of 15 elements. Better solutions are presented in other answers here.
In the following:
int *A[10];
A
is an array of 10 pointers to ints. Assuming each array element has been allocated using malloc
, you address the elements without using array notation as:
*(A+i) + j;
that is, you take A
, then take the i
th element, dereference that and add j
as the second index.
--EDIT--
And to be complete:
int foo(int *p)
here a function just receives a pointer to zero or more ints. The pointer points to a contiguous, linear block of memory into which you can place an n-dimensional array. How many dimensions there are and the upper bound of each dimension the function can only know through parameters or global variables.
To address the cells of the n-dimensional array, the programmer must calculate the addresses him/herself, using the above notation.
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;
}
回答2:
Use the *
two times. Each of *
will basically replace one []
:
*(*(matrix+i)+j)
回答3:
You can try this-
*(*(matrix+i)+j) //reduce level of indirection by using *
来源:https://stackoverflow.com/questions/35312840/how-to-print-a-2d-array-in-c-without-using-the-operator