Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function with input of pointer to pointer to

Tags:

c

pointers

sizeof

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
like image 388
limitless Avatar asked Sep 01 '16 13:09

limitless


2 Answers

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.

like image 94
Vlad from Moscow Avatar answered Oct 15 '22 16:10

Vlad from Moscow


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 chars . 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 chars. 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 chars, sizeof(**matrix3d) will print 30 Bytes.
The type of ***matrix3d is achar, sizeof(***matrix3d) will print 1 Byte.

like image 28
haccks Avatar answered Oct 15 '22 18:10

haccks