C语言-数组


数组

特点

元素个数确定;所有元素类型相同

定义

1
int numbers[10];

初始化

不初始化,元素值为无意义值;部分赋值,其它的为0

不允许用一个数组赋值另一个数组

1
2
3
4
5
6
7
8
9
10
1.
int numbers[5] = {1,2,3,4,5};
numbers[0]= 5;
2.
#include <stdio.h>
#define months 12

int days[months]={31, 29, 31, 30, 31,30,31,31,30,31,30,31}; // 用标识符常量来代表大小,修改时很方便
3.
int months[] = {1, 2, 3}; // 数组大小由括号类个数确定

指定初始化项目(C99)

1
2
3
int months[5] = {[4]=30};

int days[10] = {1, 2 ,[1]=1,2,3,4,[6]=5,6,7,8,9};

设置为只读

1
const int months[5] = {31, 29, 31,30,31}

sizeof

当定义时是没有给出数组明确大小;可以用sizeof

1
2
3
4
5
6
7
int months[] = {1, 2, 3, 4};
int i;
// sizeof后跟对象后字节大小,下例用总大小/单个大小
for(i=0; i<sizeof(months)/sizeof(months[0]); i++){
xxx
xx
}

访问

采用索引对应每一个元素

1
numbers[0];

注意索引不能超过正确范围;超过编译器不能检查出错误,有时可能程序能够正常运行,但会结果会出错,最糟糕会导致计算机锁死或重启

多维数组

1
int arr[2][2]={{1,2},{1,2}}

二维数组

分行给二维数组赋值

1
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
1
int a[3][3]={1,2,3,4,5,6,7,8,9};

对部分元素赋值

1
int a[3][3]={{1},{4,5},{}};

在不定义1维的长度下,给出二维长度

1
int a[][3]={{1,2,3},{4,5,6},{7,8,9}};
1
int a[][3]={1,2,3,4,5,6,7,8,9};
1
int a[][3]={{1,2},{4,5,6},{7}};

访问

1
2
3
4
a[1][2];
(*(a+1))[2]; // *(a+1)[2] 中括号的优先级比*高
*(*(a+1)+2);
>>>6 6 6
1
a[2]变成*(a+2); a[2][3]变成 (*(a+2))[3]再可以变成 *(*(a+2)+3)

结构数组

1
struct book library[5];

指针数组

在没学链表之前可以这么做

可以避免一次malloc申请一片连续的存储空间

1
2
struct book * fp;
fp = (struct book *) malloc(5*sizeof(struct book));
1
2
3
4
5
6
7
# define MAX 10
struct book library;
struct book * fp[MAX];
int i;
for(i=0; i<MAX; i++){
fp[i]=(struct book *)malloc(sizeof(struct book));
}

本文标题:C语言-数组

文章作者:TTYONG

发布时间:2020年08月27日 - 22:08

最后更新:2022年10月09日 - 22:10

原始链接:http://tianyong.fun/C%E8%AF%AD%E8%A8%80-%E6%95%B0%E7%BB%84.html

许可协议: 转载请保留原文链接及作者。

多少都是爱
0%