传递数组时,在C中的函数参数中强制数组大小

Mat*_*t.R 4 c arrays parameter-passing

语境

在C语言中,我有一个将数组作为参数的函数。此参数用作此函数的输出。输出总是相同的大小。我会:

  • 使任何阅读代码的人都清楚所需的大小(尽管已经在函数注释中了),
  • 理想情况下,编译可输出警告或错误,因此我可以在编译时而不是运行时防止出现问题。

潜在的解决方案

我在这里找到:https : //hamberg.no/erlend/posts/2013-02-18-static-array-indices.html看起来像解决方案的东西,但是在编译过程中我无法得到警告或错误如果我尝试传递小于所需大小的数组。

这是我完整的程序main.c:

void test_array(int arr[static 5]);

int main(void)
{
    int array[3] = {'\0'};

    test_array(array); // A warning/error should occur here at compilation-time
                       // telling me my array does not meet the required size.

    return 0;
}

void test_array(int arr[static 5])
{
    arr[2] = 0x7; // do anything...
}
Run Code Online (Sandbox Code Playgroud)

与该博客相反,我使用gcc(版本7.4.0)代替clang,并使用以下命令:

gcc -std=c99 -Wall -o main.out main.c
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我们可以看到test_array()函数需要一个5个元素的数组。我要通过一个3要素之一。我希望编译器提供有关此的消息。

在C语言中,如何强制将函数参数作为数组具有给定的大小?如果不是这样,则在编译时应该会引起注意。

Swo*_*ish 6

如果传递指向数组的指针而不是指向其第一个元素的指针,则会收到不兼容的指针警告:

void foo(int (*bar)[42])
{}

int main(void)
{
    int a[40];
    foo(&a);  // warning: passing argument 1 of 'foo' from incompatible pointer type [-Werror=incompatible-pointer-types]
    // note: expected 'int (*)[42]' but argument is of type 'int (*)[40]'

    int b[45];
    foo(&b);  // warning: passing argument 1 of 'foo' from incompatible pointer type [-Werror=incompatible-pointer-types]
    // note: expected 'int (*)[42]' but argument is of type 'int (*)[45]'
}
Run Code Online (Sandbox Code Playgroud)

编译-Werror使其出错。

哥德宝

  • 可悲的是,这种方法还会导致const正确性的问题,尤其是对于typedef,因为使指针const的直观方式会导致不兼容的指针警告/错误 (2认同)