Change
printf("%d",*matrice[i*dimColonne+j]);
to simply be
printf("%d", matrice[i][j]);
if all you're worred about is printing out the right value. After all, that's how you assigned it.
If you're doing this as an exercise to understand how array subscripting works, then there are several things you need to remember.
First, except when it is the operand of the sizeof
or unary &
operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T
" will be replaced with ("decay to") an expression of type "pointer to T
", and its value will be the address of the first element of the array. The expression matrice
is an array expression of type "20-element array of 30-element array of int
"; in most circumstances, it will be converted to an expression of type "pointer to 30-element array of int
", or int (*)[30]
. Similarly, the expression matrice[i]
is an expression of type "30-element array of int
", and in most cirumstances it will be converted to an expression of type "pointer to int
", or int *
.
Here's a handy table to remember all of this:
Declaration: T a[N];
Expression Type Decays to
---------- ---- ---------
a T [N] T *
&a T (*)[N]
*a T
a[i] T
Declaration: T a[M][N];
Expression Type Decays to
---------- ---- ---------
a T [M][N] T (*)[N]
&a T (*)[M][N]
*a T [N] T *
a[i] T [N] T *
&a[i] T (*)[N]
*a[i] T
a[i][j] T
Second, the subscripting operation a[i]
is defined as *(a + i)
; that is, you compute an address based on i
number of elements (NOT BYTES) from the base address of your array and dereference the result. For example, if a
is an array of int
, then *(a + i)
will give you the value of the i
'th integer after a
. If an is an array of struct foo
, then *(a + i)
will give you the value of the i
'th struct after a
. Pointer arithemtic always takes the size of the base type into account, so you don't need to worry about the number of bytes in the offset.
The same logic applies to multidimensional arrays, you just apply the rule recursively for each dimension:
a[i][j] == *(a[i] + j) == *(*(a + i) + j)
a[i][j][k] == *(a[i][j]+ k) == *(*(a[i] + j) + k) == *(*(*(a + i) + j) + k)
Note that you should almost never have to do these dereferences manually; a compiler knows what an array access looks like and can optimize code accordingly. Under the right circumstances, writing out the dereferences manually can result in slower code than using the subscript operator.
You can index into a 2-d array as if it were a 1-d array like so:
a[i*rows + j] = val;
but I wouldn't (the types of the expressions don't match up cleanly). Note that you multiply i
by the number of rows, not columns.