arrays - ISO/IEC 9899 :2011 6. 7.6.3 语义 7 是什么意思?

标签 arrays c undefined-behavior c11 function-declaration

首先,这是原文(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.

为了更好地理解这个问题,我写了一些代码:

#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;
}

static(int a[static 10][10]) 代表什么?
该代码的行为是否未定义?为什么?
为什么我们只需要提供对数组的第一个元素而不是全部元素的访问?

最佳答案

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

正如您提供的报价中所写:

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

是的,如果函数需要一个在大小表达式中具有指定数量的元素的数组,但该数组类型的相应参数具有较少的元素,则该函数的行为将是未定义的,因为该函数将尝试访问超出该大小的内存。数组中用作参数的元素数量。

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

我们需要至少提供对大小表达式中参数声明中指定的元素数量的访问,因为它是函数和函数用户之间的契约。该函数至少需要大小表达式中指定的元素数量。

关于arrays - ISO/IEC 9899 :2011 6. 7.6.3 语义 7 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68335893/

相关文章:

c - 如何在数组中使用指针而不是括号

Java - 是否可以对数组进行子类化?还有更多关于 Java 数组的问题

c++ - C/C++ : To access a position of a pointer of a given type is different to acess the same position of a pointer of another type?

c++ - 在gcc linux x86-64 C++中有效的指针是什么?

c++ - 带有 typeid 调用的 UB

ios - 将自定义坐标设置为函数,Waze Integration

c - 打印给定元素排列的程序

关闭从 _open_osfhandle 返回的 fd 而不关闭底层句柄

未初始化变量的 C++ 内存分配(32 位机器)

arrays - Go 中缺少数组/slice 协方差的任何明智解决方案?