传递数组时,在C中的函数参数中强制数组大小 [英] Forcing an array size in a function parameter in C when passing an array

查看:74
本文介绍了传递数组时,在C中的函数参数中强制数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In C, I have a function which take an array as a parameter. This parameter is used as an output in this function. The output is always the same size. I would:

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

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

I found here: https://hamberg.no/erlend/posts/2013-02-18-static-array-indices.html something which look like a solution but I am not able to get a warning or an error during the compilation if I try to pass a smaller array than the required size.

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

Here is my complete program 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:

Contrary to this blog, I use gcc (version 7.4.0) instead of clang with the following command:

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

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

In my code, we can see that the test_array() function needs a 5 elements array. I am passing a 3 elements one. I would expect a message from the compiler about this.

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

In C, how to force a function parameter being an array to be of a given size? In case it is not, it should be noticeable at compilation-time.

推荐答案

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

If you pass a pointer to the array instead of a pointer to its first element, you will get an incompatible pointer warning:

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 进行编译以使其成为错误.

Compile with -Werror to make it an error.

godbolt

这篇关于传递数组时,在C中的函数参数中强制数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆