我有下面的 C 代码:
#include <stdio.h>
void test(char a[2])
{
printf("%s", a);
}
int main()
{
char t[5] = {'a', 'b', 'c', 'd'};
test(t);
return 0;
}
输出:abcd
在上面的代码中,我传递了一个字符指针(大小为 5 字节的字符数组)。但是该函数的参数大小为 2 个字节 (char a[2]
)。该程序运行良好。
为什么没有编译错误或警告?这是否意味着这行 void test(char a[2])
需要 2 个字节的数组?
我和我的同事就这个问题进行了辩论。在这种情况下请赐教。
最佳答案
编译器忽略函数参数中数组第一维的大小。原型(prototype)
void test(char a[2]);
相当于
void test(char a[]);
void test(char *a);
或者您可以说编译器只是将 void test(char a[2]);
解释为 void test(char *a)
。
同样
void void test2(char a[5][5]);
相当于
void void test2(char a[][5]);
void void test2(char (*a)[5]);
关于c - 与 C 函数参数中的 char 数组大小相比,传递更大的 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47598303/