Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i retrieve 1-D array address from 2-D array?

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] ) ;
}
like image 407
abhijeet namdhari Avatar asked Feb 07 '23 21:02

abhijeet namdhari


2 Answers

#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.

like image 189
LPs Avatar answered Feb 12 '23 23:02

LPs


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.

like image 28
kwarnke Avatar answered Feb 12 '23 22:02

kwarnke