问题描述
在C语言中,这合法吗?
Is this valid in C language?
#include <stdio.h>
int main()
{
int i = 5;
int a[i]; // Compiler doesn't give error here. Why?
printf("%d",sizeof(a)); //prints 5 * 4 =20. 4 is the size of integer datatype.
return 0;
}
编译器不会在声明中给出错误 int类型的[I];
。我是不是一个常量,那么它怎么能编译成功?难道是因为我使用gcc编译器?它是允许C ++?
Compiler doesn't give error at the statement int a[i];
. i isn't a constant then how can it compile successfully? Is it because I am using gcc compiler? Is it allowed in C++?
推荐答案
是的,这是因为有效,和被称为(VLA)。换句话说,它已经在官方语言标准,大约14年。
Yes, this is valid as of C99, and is called a variable-length array (VLA). In other words, it has been in an official language standard for around 14 years.
不,这不是在C ++无效,了解详情。
No, it's not valid in C++, see this question for details.
另外请注意,的sizeof
是不是一个功能,这样就可以的printf写成(%祖\\ n,sizeof的一);
也使用了为size_t
值正确的格式说明。
Also note that sizeof
is not a function, so that can be written as printf("%zu\n", sizeof a);
which also uses the proper format specifier for a size_t
value.
这篇关于定义使用数组变量的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!