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语言中,如何强制将函数参数作为数组具有给定的大小?如果不是这样,则在编译时应该会引起注意。
如果传递指向数组的指针而不是指向其第一个元素的指针,则会收到不兼容的指针警告:
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使其出错。
| 归档时间: |
|
| 查看次数: |
111 次 |
| 最近记录: |