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 **
?
Two-dimensional (2D) arrays are indexed by two subscripts, one for the row and one for the column. Each element in the 2D array must by the same type, either a primitive type or object type.
Yes they are contiguous.
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. However, 2D arrays are created to implement a relational database lookalike data structure.
A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.
When you wrote expression
(int *)a
then logically the original array can be considered as a one-dimensional array the following way
int a[4] = { 1, 2, 3, 4 };
So expression a
points to the first element equal to 1 of this imaginary array. Expression ( a + 1 )
points to the second element of the imaginary array equal to 2 and expression ( a + 1 )[0]
returns reference to this element that is you get 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With