首页 > 解决方案 > 传递数组时在C中的函数参数中强制数组大小

问题描述

语境

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

与此博客相反,我使用 gcc(版本 7.4.0)而不是 clang 和以下命令:

gcc -std=c99 -Wall -o main.out main.c

在我的代码中,我们可以看到 test_array() 函数需要一个 5 元素数组。我正在传递一个 3 个元素。我希望编译器会收到关于此的消息。

问题

在 C 中,如何强制作为数组的函数参数具有给定大小?如果不是,它应该在编译时很明显。

标签: carraysparameter-passing

解决方案


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

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]'
}

编译-Werror使其成为错误。

神螺栓


推荐阅读