Search code examples
arrayscundefined-behaviorc11function-declaration

What is ISO/IEC 9899:2011 6.7.6.3 Semantics 7 means?


first at all, here is the original(ISO/IEC 9899:2011 6.7.6.3 Semantics 7):

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.

In order to better understand this problem, I write some code:

#include <stdio.h>

void f(int a[static 10][10])
{
    printf("0x%p\n", a);
}

int main(int argc, char *argv[])
{
    int a[][10] = {[20] = {1, 2}};
    f(a);
    int b[][10] = {{3, 4}};
    f(b);
    return 0;
}

what is that static(int a[static 10][10]) stand for?
Is the behavior of that code undefined? why?
Why do we only need to provide access to the first element of an array not all of it?


Solution

  • what is that static(int a[static 10][10]) stand for?

    As it is written in the quote provided by you:

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

    Is the behavior of that code undefined? why?

    Yes, the behavior of a function will be undefined if it expects an array with the specified number of elements in the size expression but the corresponding argument of the array type has fewer elements, because the function will try to access memory beyond the number of elements in the array used as an argument.

    Why do we only need to provide access to the first element of an array not all of it?

    We need to provide access at least to the number of elements specified in the parameter declaration in the size expression because it is a contract between the function and the user of the function. The function expects at least the number of elements specified in the size expression.