limitless limitless - 3 months ago 10
C Question

Function with input of pointer to pointer to

I saw this question about the the result of

sizeof()
and i didn't understand the output of this function.

#include <stdio.h>
void checkSizes(char matrix3d[10][20][30])
{
printf ("%lu\t", sizeof(matrix3d));
printf ("%lu\t", sizeof(*matrix3d));
printf ("%lu\t", sizeof(**matrix3d));
printf ("%lu\t", sizeof(***matrix3d));
}
int main()
{
char matrix[10][20][30];
checkSizes(matrix);
}


as i was assuming , when a function get an array to work with , it's getting a pointer to the array, so when i'll print the first line of

printf ("%lu\n", sizeof(matrix3d));


the output will be 8.

BUT
isn't the next printf will get me to diffrent pointer to pointer that his size will be also 8 ?

so i thouth this will lead to

8 8 8 1


the real output is

8 600 30 1

Answer

In this statement

printf ("%lu\t", sizeof(*matrix3d));
// it is better to use "%zu\t"

expression *matrix3d has type char[20][30].

Using an array in the sizeof operator as an expression does not convert the expression to the pointer to the first element of the array.

Thus you will get output 600.

However if you would write

sizeof( *matrix3d + 0)

then indeed *matrix3d having type char[20][30] will be converted in the expression *matrix3d + 0 implicitly to pointer of type char ( * )[30] and the corresponding printf statement will output 8,

As for the function parameter and its argument then they are implicitly converted to type char ( * )[20][30]

So for example these function declarations are equivalent

void checkSizes(char matrix3d[10][20][30]);
void checkSizes(char ( *matrix3d )[20][30]);

and declare the same one function.