c语言中声明数组时, 元素个数必须使用常量表达式
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
。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2023-11-06 linux 中查看GNU c库版本 libc.so.6(GLIBC版本)
2023-11-06 configure: error: You need zlib >= 1.2.3 to build bin/PopLDdecay
2023-11-06 conda 升级到最新版本
2023-11-06 centos7 中 安装 rmblast 软件
2022-11-06 python中os模块下路径的常见操作
2021-11-06 docker pull越来越慢的解决方法
2021-11-06 Vmware虚拟机和docker在win10上不兼容的处理