I'm completely new to programming. This code is not working as I want, which is to retrieve 1-D array address from 2-D array:
#include<stdio.h>
main() {
int s[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};
int i ;
for ( i = 0 ; i <= 3 ; i++ )
printf ( "\nAddress of %d th 1-D array = %u", i, s[i] ) ;
}
#include<stdio.h>
int main( )
{
int s[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
} ;
int i ;
for ( i = 0 ; i < 4 ; i++ )
printf ( "\nAddress of %d th 1-D array = %p\n", i, (void *)s[i] ) ;
return 0;
}
As you can see in posted code use %p
format to print addresses. This format specifier wants a void *
as passed parameter.
To be more precise and not using the C feature that an array is passed by a pointer to a function (printf()
here), you can use a pointer to an array here:
for ( i = 0 ; i < 4 ; i++ ) {
int (*ptr)[2] = &(s[i]);
printf ( "\nAddress of %d th 1-D array = %p\n", i, (void*)ptr) ;
}
The difference between s[i]
and &(s[i])
is, that s[i]
is the 1d array, the type is int[2]
, where &(s[i])
is a pointer to int[2]
, what you want here.
You can see it, for example, with the sizeof
operator: sizeof(s[i])
is 2 * sizeof(int)
here, where sizeof(&(s[i]))
has the size of a pointer variable.
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