Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sizeof applied to parameter of incomplete array type

For this code:

int f(int x[])
{
    return sizeof x;
}

GCC produces:

warning: 'sizeof' on array function parameter 'x' will return size of 'int *'

Clang produces:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

warning: sizeof on array function parameter will return size of 'int *' instead of 'int[]'

Question: if x has incomplete type (since the size is not present), then is it expected to have:

error: invalid application of 'sizeof' to incomplete type

Extra: does it mean that return size of 'int *' is a GCC/Clang extension?

>Solution :

An array as an argument to a function is actually a pointer. From section 6.7.6.3p7 of the C standard regarding Function Declarators:

A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to
type’’,
where the type qualifiers (if any) are those specified within the [ and ] of the
array type derivation. If the keyword static also appears within the [ and ] of the
array type derivation, then for each call to the function, the value of the corresponding
actual argument shall provide access to the first element of an array with at least as many
elements as specified by the size expression.

This means that this:

int f(int x[])
{
    return sizeof x;
}

Is exactly the same as this:

int f(int *x)
{
    return sizeof x;
}

So x does have complete type and there is no error. Both gcc and clang are being helpful in generating a warning as the result might not be what one expects.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading