001、
[root@PC1 test]# ls test.c [root@PC1 test]# cat test.c ## 测试程序 #include <stdio.h> int main(void) { int var1 = 5; // 初始化一个变量var1 int array1[var1] = {3,5,8,4,9}; // 初始化数组 return 0; } [root@PC1 test]# gcc test.c -o kkk ## 无法进行编译,说明声明数组个数时,必须使用常量表达式 test.c: In function ‘main’: test.c:7:2: error: variable-sized object may not be initialized int array1[var1] = {3,5,8,4,9}; ^ test.c:7:2: warning: excess elements in array initializer [enabled by default] test.c:7:2: warning: (near initialization for ‘array1’) [enabled by default] test.c:7:2: warning: excess elements in array initializer [enabled by default] test.c:7:2: warning: (near initialization for ‘array1’) [enabled by default] test.c:7:2: warning: excess elements in array initializer [enabled by default] test.c:7:2: warning: (near initialization for ‘array1’) [enabled by default] test.c:7:2: warning: excess elements in array initializer [enabled by default] test.c:7:2: warning: (near initialization for ‘array1’) [enabled by default] test.c:7:2: warning: excess elements in array initializer [enabled by default] test.c:7:2: warning: (near initialization for ‘array1’) [enabled by default]
。
002、验证
[root@PC1 test]# ls test.c [root@PC1 test]# cat test.c ## 测试程序 #include <stdio.h> int main(void) { int var1 = 5; int array1[5] = {3,5,8,4,9}; // 这里数组个数修改为常量 return 0; } [root@PC1 test]# gcc test.c -o kkk ## 可以编译了 [root@PC1 test]# ls kkk test.c
。
003、使用对象式宏
[root@PC1 test]# ls test.c [root@PC1 test]# cat test.c #include <stdio.h> #define NUMBER 5 // 定义了一个对象式宏 int main(void) { int var1 = 5; int array1[NUMBER] = {3,5,8,4,9}; //使用对象式宏变量 return 0; } [root@PC1 test]# gcc test.c -o kkk ## 编译 [root@PC1 test]# ls kkk test.c
。
标签:常量,int,PC1,个数,default,warning,test,root,表达式 From: https://www.cnblogs.com/liujiaxin2018/p/18530864