Search code examples
cpointersmultidimensional-arrayimplicit-conversiondereference

Pointers application in C array


I write down below code exactly, and it's supposed to yield "2036, 2036, 2036" but it keeps returning 8-9 digits weird random value whenever I press "Run" button repeatedly.

Anyone knows about it?

 #include <stdio.h>
 int main() 
  { 
  unsigned int x[4][3] = {{1, 2, 3}, {4, 5, 6}, 
                       {7, 8, 9}, {10, 11, 12}};
  printf("%u, %u, %u", x+3, *(x+3), *(x+2)+3);
  } 

Solution

  • You declared a two-dimensional array

    unsigned int x[4][3] = {{1, 2, 3}, {4, 5, 6}, 
                            {7, 8, 9}, {10, 11, 12}};
    

    Used in the argument expressions in the call pf printf

    printf("%u, %u, %u", x+3, *(x+3), *(x+2)+3);
    

    it is implicitly converted to a pointer to its first element of the type unsigned int ( * )[3].

    So x + 3 is a pointer to the forth row of the array that you are trying to output as an unsigned int that results in undefined behavior.

    The expression *( x + 3 ) yields the forth row of the array that is implicitly converted to a pointer to the first element of the row. So the address of the first element of the forth row of the array is outputted as an unsigned int that again invokes undefined behavior.

    The expression *(x+2) gives the first element of the third row as it is described above. So the expression *(x+2)+3 yields the address of the memory after the last element of the third row.

    Just rewrite the call of printf like

    printf("%p, %u, %u\n", ( void * )( x+3 ), **(x+3), **(x+2)+3);
    

    And you will get the address of the forth row, the value of the first element of the forth row (10) and the value of the first element of the third row (7) plus 3 that is 10.

    Otherwise you need to write

    printf("%p, %p, %p\n", ( void * )( x+3 ), ( void * )( *(x+3) ), ( void * )( *(x+2)+3 ) );
    

    to output the original expression that have pointer types.