1、记得最初学C语言时,关于数组有这么一点:定义数组时,其长度不能用变量来表示。
但是今天一不小心写错了:char buf[len],居然编译通过,运行正确!
简单的测试程序,array_init.c如下:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
int len = argc > 1 ? atoi(argv[1]) : 0;
char buf[len+1];
printf("buf length is : %d\n", (int)sizeof(buf));
printf("please input string:\n");
//scanf("%s", buf);
fgets(buf, len, stdin);
printf("the input string is : %s\n", buf);
return 0;
}
执行时,
$./a.out 10
buf length is : 11
please input string:
abcdefghjklmn
the input string is : abcdefghj网上查了一下,有人说是C89不支持 数组长度用变量,而C99支持。
参考:https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
2、但是,这里还有一个问题
若将代码稍微改动一下,在声明数组时初始化
char buf[len + 1] = {"abcdefg"};这时候,编译报错:
error: variable-sized object may not be initialized
3、此时,再将源文件的后缀名 改为 .cpp,即为array_init.cpp,
#include <stdio.h>
#include <cstdlib>
int main(int argc, char *argv[]){
int len = argc > 1 ? atoi(argv[1]) : 0;
char buf[10+1] = {"abcdef"};
printf("buf length is : %d\n", (int)sizeof(buf));
printf("please input string:\n");
fgets(buf, len, stdin);
printf("the input string is : %s\n", buf);
return 0;
}这时编译通过,运行正确
其中原因还没有搞清楚,待日后再仔细琢磨
本文探讨了C99标准下变长数组的使用情况,包括数组长度由变量指定时的编译及运行表现,并对比了初始化时的不同行为。此外还涉及了C++环境下相同代码的表现差异。
435

被折叠的 条评论
为什么被折叠?



