Behavior of 2D arrays
arrays, c, c++, output, pointers
Solution
Are my assumptions correct or is there some other logic behind this?
Yes.
`*(a+1)[0]` is equivalent to `a[1][0]`. `((int *)a+1)[0]` is equivalent to `a[0][1]`.
Explanation:
`a` decays to pointer to first element of 2D array, i.e to the first row. `*a` dereferences that row which is an array of 2 `int`. Therefore `*a` can be treated as an array name of first row which further decay to pointer to its first element, i.e `1`. `*a + 1` will give the pointer to second element. Dereferencing `*a + 1` will give `1`. So:
((int *)a+1)[0] == *( ((int *)a+1 )+ 0)
== *( ((int *)a + 0) + 1)
== a[0][1]
Note that `a`, `*a`, `&a`, `&a[0]` and `&a[0][0]` all have the same address value although they are of different types. After decay, `a` is of type `int (*)[2]`. Casting it to `int *` just makes the address value to type `int *` and the arithmetic `(int *)a+1` gives the address of second element.
Also, originally what is the type of a when treated as pointer `(int (*)[2]` or `int **`?
It becomes of type pointer to array of 2 `int`, i.e `int (*)[2]`
Problem
I have created a 2D array, and tried to print certain values as shown below: ``` int a[2][2] = { {1, 2}, {3, 4}}; printf("%d %d\n", *(a+1)[0], ((int *)a+1)[0]); ``` The output is: ``` 3 2 ``` I understand why `3` is the first output (`a+1` points to the second row, and we print its `0th` element. My question is regarding the second output, i.e., `2`. My guess is that due to typecasting `a` as `int *`, the 2D array is treated like a 1D array, and thus `a+1` acts as pointer to the `2nd` element, and so we get the output as `2`. Are my assumptions correct or is there some other logic behind this? Also, originally what is the type of `a` when treated as pointer `int (*)[2]` or `int **`?