Search code examples
cpointersmultidimensional-arrayprintfconversion-specifier

Pointers with multi dimensional arrays in C


int array[2][3] = {{2,3,6},{4,5,8}};

printf("%d\n",*array);

What will be the output of this and please explain how?

Regards,

Winston


Solution

  • Educate yourself on multidimensional arrays.

    Array array is a 2D array:

    int array[2][3] = {{2,3,6},{4,5,8}};
    

    *array is the first element of array array because

    *array -> * (array + 0) -> array[0]
    

    The first element of array array is array[0], which is {2,3,6}. The type of array[0] is int [3]. When you access an array, it is converted to a pointer to first element (there are few exceptions to this rule).

    So, in this statement

    printf("%d\n",*array);
    

    *array will be converted to type int *. The format specifier %d expect the argument of type int but you are passing argument of type int *. The compiler must be throwing warning message for this. Moreover, wrong format specifier lead to undefined behaviour.

    If you want to print a pointer, use %p format specifier. Remember, format specifier %p expect that the argument shall be a pointer to void, so you should type cast pointer argument to void *.