Can I get a 1-dimensional array address from a 2-dimensional array?

I am completely new to programming. This code does not work the way I want to get a 1-D array address from a 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] ) ;
}
+4
source share
2 answers

To be more precise and not use the C function, so that the 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 it s[i] is a 1d array, a type int[2]where &(s[i])is a pointer to int[2]what you want here.

, , sizeof: sizeof(s[i]) is 2 * sizeof(int) , sizeof(&(s[i])) .

+2
#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;
}

, %p . void * .

+6

Source: https://habr.com/ru/post/1626489/


All Articles