-2
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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
winstonbrown
  • 70
  • 1
  • 6
  • Does this answer your question? [Two dimensional arrays and pointers](https://stackoverflow.com/questions/8669773/two-dimensional-arrays-and-pointers) – lbarqueira Feb 03 '22 at 09:24
  • 2
    `"%d"` and `*array` are incompatible. The first expects a value of type `int`, the latter has type `int[3]` ==> **Undefined Behaviour!** – pmg Feb 03 '22 at 09:27
  • 1
    Any chance this is a homework or exam question? – Mario Feb 03 '22 at 09:27
  • "What will be the output of this" What prevents you from running it and see for yourself? – Lundin Feb 03 '22 at 13:14

2 Answers2

0

This call of printf

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

invokes undefined behavior because there is used incorrect conversion specifier %d with a pointer expression.

If you will write instead

printf("%p\n", ( void * )*array);

then there will be outputted the address of the extent of memory occupied by the array that is the address of the first element of the array.

That is the expression *array has the type int'[3]. Used as an argument in the call of printf it is implicitly converted to pointer to the first element of the type int *. It is the same as to write

printf("%p\n", ( void * )&array[0][0]);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

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

H.S.
  • 11,654
  • 2
  • 15
  • 32