Friday, 8 December 2017

Understand the 2nd Array size, access &




#include <stdio.h>


int main()
{
    int arr[4][3] = { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};


        printf("Vel arr[0] = %p (arr+1) = %p *(arr+1) = %p \n", arr[0], (arr +1), *(arr+1));



        // Below 2 contain the following same warning
/*array_2d_understand.c:12:9: warning: format ‘%p’ expects argument of type ‘void *’, but argument 4 has type ‘int’ [-Wformat=]
  printf("Vel arr[1] = %p arr[1] = %p arr[1][1] = %p \n", arr[1], arr[1], arr[1][1]); */ 
       printf("Vel arr[1] = %p arr[1] = %p arr[1][1] = %p \n", arr[1], arr[1], arr[1][1]);

        printf("Vel *((arr +1)+1) = %p *(arr+2) = %p *(*(arr +1) +1) = %p arr[1][1] = %p \n", *((arr +1)+1), *(arr+2), *(*(arr +1) +1), arr[1][1]);
        printf("Vel (*(arr +1) +1) = %p &arr[1][1] = %p \n", (*(arr +1) +1), &arr[1][1]);


        printf("\n\n\tarr[4][3] = { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}} \n");
        printf(" \n\t Understand : (arr+1) != *(arr+1) The address of this 2 output will be same \n\t"
               "but they are not equal because arr+1 is a 2nd  array arr is incremented by 1 Hence further\n\t"
               " increment is incremented by 3 but *(arr+1) is 2nd array is now converted to 1D arry because of \n\t"
               "* hence further increment is only sizeof int. \n");
}







Output:
Vel arr[0] = 0xbfcafb6c (arr+1) = 0xbfcafb78 *(arr+1) = 0xbfcafb78
Vel arr[1] = 0xbfcafb78 arr[1] = 0xbfcafb78 arr[1][1] = 0x5
Vel *((arr +1)+1) = 0xbfcafb84 *(arr+2) = 0xbfcafb84 *(*(arr +1) +1) = 0x5 arr[1][1] = 0x5
Vel (*(arr +1) +1) = 0xbfcafb7c &arr[1][1] = 0xbfcafb7c


    arr[4][3] = { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}}

     Understand : (arr+1) != *(arr+1) The address of this 2 output will be same
    but they are not equal because arr+1 is a 2nd  array arr is incremented by 1 Hence further
     increment is incremented by 3 but *(arr+1) is 2nd array is now converted to 1D arry because of
    * hence further increment is only sizeof int.

~                             

No comments:

Post a Comment