c - 传递数组时在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 中,如何强制作为数组的函数参数具有给定大小?如果不是,它应该在编译时很明显。
解决方案
如果传递指向数组的指针而不是指向其第一个元素的指针,则会收到不兼容的指针警告:
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
使其成为错误。
推荐阅读
- c# - 来自 C# 的 gandi api 调用返回 400。Postman 的工作正常
- ef-core-3.0 - Entity Framework Core 3.0:在运行时修改配置的全局查询
- vue.js - 错误的组件结构 - 道具问题
- javascript - 如何理解这个 Promise 执行顺序?
- nginx - 如何将子域位置分配给 Nginx 中的子路径?
- unix - 在 vi 中添加行号并在 vi 中连接文件
- android - 我的 ListPreference 在运行时不会更改应用程序主题
- ruby-on-rails - 如何将 mxgraph 集成到 webpack 中?
- java - 在运行时更改 bean 类名
- sql - SQL - 仅将每个单词的第一个字母大写,其余全部小写