c语言中数组的声明与初始化

 

001、数组的声明

 

01、数组的声明包括数组元素的类型,数组元素的类型只能是一种。

02、数组的名称;比如 array1

03、数组的大小(长度)

复制代码
[root@PC1 test]# ls
test.c
[root@PC1 test]# cat test.c           ##   测试c程序
#include <stdio.h>

int main(void)
{
        int array[3];                 // 数组元素的类型为int; 数组的名称为array; 数组元素的个数为3;

        array[0] = 100;              // 数组元素的赋值
        array[1] = 500; 
        array[2] = 887;

        int i;

        for(i = 0; i < 3; i++)                         // 数组的遍历
        {
                printf("array[%d] = %d\n", i, array[i]);
        }

        return 0;
}
[root@PC1 test]# gcc test.c -o kkk                ## 编译
[root@PC1 test]# ls
kkk  test.c
[root@PC1 test]# ./kkk                          ## 运算
array[0] = 100
array[1] = 500
array[2] = 887
复制代码

 。

 

002、数组的初始化

a、直接初始化

复制代码
[root@PC1 test]# ls
test.c
[root@PC1 test]# cat test.c                                ## 测试c程序
#include <stdio.h>

int main(void)
{
        int array[3] = {3,7,98};                         //初始化, 在声明的基础上直接用中括号添加int i;

        for(i = 0; i < 3; i++)
        {
                printf("array[%d] = %d\n", i, array[i]);
        }

        return 0;
}
[root@PC1 test]# gcc test.c -o kkk
[root@PC1 test]# ls
kkk  test.c
[root@PC1 test]# ./kkk                                 ## 运算测试
array[0] = 3
array[1] = 7
array[2] = 98
复制代码

 。

 

b、

复制代码
[root@PC1 test]# ls
test.c
[root@PC1 test]# cat test.c                    ## 测试c程序
#include <stdio.h>

int main(void)
{
        int ay[6] = {3, 8, 4};               // 声明数组的大小是6, 但是初始化只给3个元素,会出现什么情况int i;

        for(i = 0; i < 6; i++)
        {
                printf("ay[%d] = %d\n", i, ay[i]);
        }

        return 0;
}
[root@PC1 test]# gcc test.c -o kkk
[root@PC1 test]# ls
kkk  test.c
[root@PC1 test]# ./kkk                         ## 测试,剩余的值会用0来代替
ay[0] = 3
ay[1] = 8
ay[2] = 4
ay[3] = 0
ay[4] = 0
ay[5] = 0
复制代码

 

c、初始话数组的元素全部为0

复制代码
[root@PC1 test]# ls
test.c
[root@PC1 test]# cat test.c             ## 测试c程序
#include <stdio.h>

int main(void)
{
        int ay[6] = {};                 //  初始话数组的元素全部为0

        int i;

        for(i = 0; i < 6; i++)
        {
                printf("ay[%d] = %d\n", i, ay[i]);
        }

        return 0;
}
[root@PC1 test]# gcc test.c -o kkk
[root@PC1 test]# ls
kkk  test.c
[root@PC1 test]# ./kkk                   ## 运算测试
ay[0] = 0
ay[1] = 0
ay[2] = 0
ay[3] = 0
ay[4] = 0
ay[5] = 0
复制代码

 。

 

posted @   小鲨鱼2018  阅读(150)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2022-10-27 python 脚本统计fasta文件每条scaffold的碱基长度
2022-10-27 linux 中 shell 统计每条scaffold的长度
2022-10-27 linux 中 wc -c命令
2022-10-27 linux 系统中如何判断字符串是否相同
2021-10-27 R语言中%*%运算符
2021-10-27 windows中如何查看端口占用情况、端口是否开启
2021-10-27 R语言中setdiff、intersect、union函数
点击右上角即可分享
微信分享提示