文章目录
1. 数组定义
数组是存储一个固定大小的并且具有相同类型元素的顺序集合。
- 定义
类型 数组名[元素个数];
如:int arr[5];
在C中要定义一个数组,需要指定元素的类型和元素的数量。在C99中,可以使用整型变量作为元素个数;在C89中,只能使用整型常量。
2. 数组的使用
2.1 初始化数组
数组与变量、指针一样,使用前都需要进行初始化。
- 初始化
类型 数组名[元素个数] = {值1,值2,值3,值4,等等};
例如:int arr[5] = {1,2,3,4,5};
- 初始化的注意事项
(1) 初始化时,元素的个数不能超过定义的数组元素个数,否则会产生报错;
(2) 如果进行数组部分初始化,则未初始化的元素值为0。
#include <stdio.h>
int main(){
int arr[5]={
1,2,3};
for(int i=0;i<5;++i){
printf("%d\n",arr[i]);
}
}
- 简单初始化
初始化数组可以不指定数组大小,此时数组的大小则为初始化时元素的个数。例如:
int arr[] = {1,2,3,4,5};
- (1) 数组未初始化,数组里面的值都是随机值
#include<stdio.h>
int main(){
int arr[12];
for(int i=0;i<12;++i){
printf("%d ",arr[i]);
}
printf("\n");
}
- 运行结果
[root@localhost C2_01]# ./a.out
0 0 4195949 0 746897568 32688 0 0 4195872 0 4195568 0
[root@localhost C2_01]#
- (2)数组初始化为{0},数组里面的值都是0
include<stdio.h>
int main(){
int arr[12] = {
0};
for(int i=0;i<12;++i){
printf("%d ",arr[i]);
}
printf("\n");
}
- 运行结果
[root@localhost C2_01]# gcc test_int6.c
[root@localhost C2_01]# ./a.out
0 0 0 0 0 0 0 0 0 0 0 0
[root@localhost C2_01]#
- (3)数组初始化为{非零值},数组里面第一个值是非零值,其他的值都是0
nclude<stdio.h>
int main(){
int arr[12] = {
2};
for(int i=0;i<12;++i){
printf("%d ",arr[i]);
}
printf("\n");
}
- 运行结果
[root@localhost C2_01]# gcc test_int7.c
[root@localhost C2_01]# ./a.out
2 0 0 0 0 0 0 0 0 0 0 0
[root@localhost C2_01]#
- (4)指定下标的值被赋值,其他的值都是0(这是C99语法)
#include<stdio.h>
int main(){
int arr[12] = {
[1]=1,[5]=5};
for(int i=0;i<12;++i){
printf("%d ",arr[i]);
}
printf("\n");
}
- 运行结果
[root@localhost C2_01]# gcc test_int7.c
[root@localhost C2_01]# .