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
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.
First you need to know that sizeof
is an operator and not a function. Arrays do not convert to pointer to its first element when it is an operand of sizeof
or unary &
operator.
In function checkSizes
, the parameter matrix3d
is of type pointer to an array of 20 arrays of 30 char
s . Since it is a pointer, the statement
printf ("%lu\t", sizeof(matrix3d));
will print the size of a pointer.
Dereferencing the pointer matrix3d
will give its first element. Its first element is an array of 20 arrays of 30 char
s. sizeof(*matrix3d)
will return size of array char[20][30]
which is 600 Bytes. sizeof(*matrix3d)
is equivalent to sizeof(matrix3d[0])
.
The type of **matrix3d
is an array of 30 char
s, sizeof(**matrix3d)
will print 30 Bytes.
The type of ***matrix3d
is achar
, sizeof(***matrix3d)
will print 1 Byte.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With