Home > Software design >  Pointers with multi dimensional arrays in C
Pointers with multi dimensional arrays in C

Time:02-03

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

CodePudding user response:

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]);

CodePudding user response:

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

  •  Tags:  
  • Related