My Problem with the following Code:
int main() {
int i = 0;
int array[2][2] = { {1,2} , {3,4}};
for(int j = 0; j<2; j ) {
for(int k = 0; k < 2;k ) {
printf("%d", *(*(*(array i) j) k));
}
printf("\n");
}
}
Why doesn't this work?
My thought: I have the i^th 2 d array (which is 0, because i have only one 2d array), then the j^th 1d array of the i^th 2d array and so the k^th element of the j^th 1d array of the i^th 2d array.
Thank you very much.
CodePudding user response:
Arrays used in expressions with rare exceptions are implicitly converted to pointers to their first elements.
From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.
You have the following two-dimensional array
int array[2][2] = { {1,2} , {3,4}};
the elements of the array are in turn one dimensional arrays of the type int[2]
.
So the array designator used in the call of printf
is converted to a pointer to its first element (row ) of the type int( * )[2]
.
To get a pointer to the i-th row of the array using the pointer arithmetic you should write
array i
The expression as already mentioned has the type int ( * )[2]
.
Dereferencing the pointer expression
*( array i )
you will get its i-th row that is an array of the type int[2]
that in turn is converted to a pointer of the type int *
to its first element.
To get a pointer to the j-th element of the row using the pointer arithmetic you should write
*( array i ) j
the expression has the type int *
.
So to get the element pointed to by the pointer expression you need to dereference it like
*( *( array i ) j )
Thus the nested for loops will look like
for( int i = 0; i < 2; i )
{
for ( int j = 0; j < 2; j )
{
printf("%d", *( *( array i ) j ) );
}
printf("\n");
}
CodePudding user response:
*(array i)
gives you the i
'th 1D array, not the i
'th 2D array.
The expression *(array i)
has type int [2]
, which decays to int *
. Therefore, the expression *(*(array i) j)
has type int
, which cannot be further dereferenced. Remember, if
a[i] == *(a i)
then
a[i][j] == *(a[i] j) == *(*(a i) j)
and
a[i][j][k] ==
*(a[i][j] k) ==
*(*(a[i] j) k) ==
*(*(*(a i) j) k)
etc.
For your sanity and everyone else's, just use array subscript notation. Exercises like this are good for understanding how array subscripting actually works in C, but subscript notation is cleaner and you're less likely to make a mistake.