Context
在 C 中,我有一个以数组作为参数的函数。该参数用作该函数的输出。输出的大小始终相同。我会:
- 让阅读代码的人清楚所需的大小(不过它已经在函数注释中了),
- 理想情况下,编译会输出警告或错误,这样我就可以在编译时而不是运行时防止出现问题。
一个潜在的解决方案
我在这里找到:https://hamberg.no/erlend/posts/2013-02-18-static-array-indices.html 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 元素一。我希望编译器会就此发出一条消息。
Question
在C中,如何强制作为数组的函数参数具有给定的大小?如果不是,它应该在编译时显而易见。
如果您传递指向数组的指针而不是指向其第一个元素的指针,您将收到不兼容的指针警告:
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
使其成为错误。
godbolt https://godbolt.org/z/kqlMTr
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)