#include <stdio.h>
int main ()
{
int arr[4][5] = {{1, 2, 3, 4, 5},
{6, 7,8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17,18, 19, 20}
};
printf("%p\n", arr);
printf("%p\n",*arr);
return(0);
}
My doubt is that when I print arr and *arr it is printing same value. Why is this happening?
arr
is an array of arrays of int
. As per the array to pointer conversion rule, arr
in printf(“%p\n”, arr);
will decay to pointer to its first element. First element of array arr
is of type int [5]
, ie an array of 5 int
. Therefore, it will print the address of first element of the array arr
(address of arr[0]
).
Dereferencing, arr
will return the first element of arr
. This first element is of type int [5]
as discussed earlier. So *arr
will return an array of 5 int
but again as per the array to pointer conversion rule *arr
will decay to pointer to it's first element which is arr[0][0]
.
So, in fact first printf
is printing the address of the array arr[0]
while later prints the address of the element arr[0][0]
.
To understand why both these addresses are same I would suggest you to read this post .
printf("%p\n", arr);
printf("%p\n",*arr);
At the first example, arr
decays to a pointer to the first element in the first dimension of the two-dimensional array arr
(the first int
array of 5 elements - type ( int[5]
)) which also decays to a pointer to its first element which is a[0][0]
.
At the second example you explicitly address the first element of the first dimension (which is of type int[5]
- int
array of 5 elements) and this one also decays to a pointer to its first element, which is again a[0][0]
.
So both have exactly the same result - Access and print the address of the first element of the first array at the first dimension of arr
- arr[0][0]
.
Note that you need to cast the pointer to void
, to make the program C-standard-conform as the standard implies that the %p
format specifier needs to have an associated argument of type void*
:
printf("%p\n", (void*) arr);
printf("%p\n", (void*) *arr);
Quote from ISO:IEC 9899:2018 (C18), Section 7.21.6.1/8:
"p - The argument shall be a pointer to void . The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner."
because you should know that name of any array means the first address of this array say
int arr[4];
printf("%p",arr);// the same as printf("%p",&arr[0]);
and with respect to 2D array also the name of array acts as visuals pointer which points to the address of the first element in array
int arr[4][5];
printf("%p",&arr[0][0]);//the same as printf("%p",arr);=printf("%p"*arr);
```````````````
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.