为什么这个C code是有效的GCC - 在结构的中间变量长度数组 [英] Variable length array in the middle of struct - why this C code is valid for gcc
本文介绍了为什么这个C code是有效的GCC - 在结构的中间变量长度数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一些奇怪的code(VLAIS),这是由GCC 4.6视为有效C(C99,C11):
$猫交流转换器
INT主(INT ARGC,字符** argv的)
{
结构args_t {
int类型的;
INT PARAMS [ARGC] //<<笏?
// VLA一些结构的中间,其他领域之间
INT B:
} ARGS; args.b = 0; 为(args.a = 0; args.a&下;的argc; args.a ++)
{
args.params [args.a] = argv的[0] [0];
args.b ++;
}
返回args.b;
}
这code无警告编译:
$ GCC-4.6 -Wall -std = C99交流转换器和放大器;&安培;回声$?
0
$ ./a.out;回声$?
1
$ ./a.out 2;回声$?
2
$ ./a.out 2 3;回声$?
3
同为 -std = C1X
:
$ GCC-4.6 -Wall -std = C1X交流转换器和放大器;&安培;回声$?
0
但是,这并不与英特尔C编译器或锵+ LLVM工作:
$ ICC交流转换器-o a.icc
交流转换器(5):警告#1361:变长数组字段类型将被视为零长度的数组字段类型
INT PARAMS [ARGC]
^
$ ./a.icc;回声$?
47$铛交流转换器-o a.clang
交流转换器:5:10:错误:字段必须有一个固定的大小:扩展名结构中的可变长度阵'将永远不会得到支持
INT PARAMS [ARGC]
^
产生1个错误。
所以:
- 为什么这是由GCC视为有效code?
- 如果它是GCC的延伸,在那里它被描述?
- 难道是C99和C11 ISO标准是否有效?
解决方案
GCC不允许它,编译 -std = C99 -pedantic-错误
。一个结构内部的VLA显然是(不良记录)非标准GNU C功能。 看到这个。
There is some strange code (VLAIS) which is treated as Valid C (C99, C11) by gcc 4.6:
$ cat a.c
int main(int argc,char**argv)
{
struct args_t{
int a;
int params[argc]; // << Wat?
// VLA in the middle of some struct, between other fields
int b;
} args;
args.b=0;
for(args.a=0;args.a<argc;args.a++)
{
args.params[args.a]=argv[0][0];
args.b++;
}
return args.b;
}
This code compiled without warnings:
$ gcc-4.6 -Wall -std=c99 a.c && echo $?
0
$ ./a.out ; echo $?
1
$ ./a.out 2; echo $?
2
$ ./a.out 2 3; echo $?
3
Same for -std=c1x
:
$ gcc-4.6 -Wall -std=c1x a.c && echo $?
0
But this not work with Intel C Compiler or with Clang+LLVM:
$ icc a.c -o a.icc
a.c(5): warning #1361: variable-length array field type will be treated as zero-length array field type
int params[argc];
^
$ ./a.icc; echo $?
47
$ clang a.c -o a.clang
a.c:5:10: error: fields must have a constant size: 'variable length array in structure' extension will never be supported
int params[argc];
^
1 error generated.
So:
- Why this is considered as valid code by GCC?
- If it is an extension of GCC, where it is described?
- Is it valid in C99 and C11 ISO Standards?
解决方案
GCC does not allow it, compile with -std=c99 -pedantic-errors
. A VLA inside a struct is apparently a (poorly documented) non-standard GNU C feature. See this.
这篇关于为什么这个C code是有效的GCC - 在结构的中间变量长度数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文