一维数组
遵循规则
- 数组名的命名规则和变量名的相同,即遵循标识符命名规则。
- 在定义数组时,需要指定数组中元素的个数,方括号中的常量表达式用来表示元素的个数,即数组长度。
- 常量表达式中可以包含常量和符号常量,但不能包含变量。也就是说,C语言不允许对数组的大小做动态定义,即数组的大小不依赖于程序运行过程中变量的值。
在内存中的存储
#include <stdio.h>
int main() {
int a[10] = {0,1,2,3,4,5,6,7,8,9};
}
数组访问越界与数组的传递
数组的访问越界
#include <stdio.h>
//访问越界
int main() {
int a[5] = {1,2,3,4,5};
int j = 20;
int i = 10;
a[5] = 6;//访问越界
a[6] = 7;
printf("i = %d\n",i);//i我们并灭有赋值,但值却变化了
return 0;
}
//输出
i = 7
数组的传递
#include <stdio.h>
//一维数组的传递
//数组名传递到子函数后,子函数的形参接收到的是数组的起始地址,因此不能把数组的长度传递给子函数
void print(int a[],int length){
int i;
for(i = 0;i < length;i++){
printf("%d\t",a[i]);
}
a[3]=20;
printf("\n");
}
int main() {
int a[6] = {1,2,3,4,5};
print(a,5);//数组在传递给子函数时,数组长度是传递不过去的
printf("a[3] = %d\n",a[3]);
return 0;
}
//输出
1 2 3 4 5
a[3] = 20
字符数组与scanf读取字符串
字符数组初始化及传递
#include <stdio.h>
//模拟printf("%s",c)操作
void print(char d[]) {
int i = 0;
while (d[i]) {//当走到结束符时,循环结束
printf("%c", d[i]);
i++;
}
printf("\n");
d[0]='H';
}
//输出字符串乱码时,要去查看字符数组中是否存储了结束符'\0'
int main() {
char c[9] = "Iamhappy";
char d[5] = "how";
printf("%s\n",c);
print(d);
printf("%s\n",d);
return 0;
}
scanf读取字符串
#include <stdio.h>
//scanf读取字符串,会自动往字符数组中放结束符
int main() {
char c[10];
char d[10];
scanf("%s%s",c,d);//字符数组名c中存储了数组的起始地址,因此不需要取地址
printf("c = %s,d = %s\n",c,d);
return 0;
}
gets与puts,strlen-strcmp-strcopy-stecat
gets函数与puts函数
gets函数的格式: char *gets(char *str);
puts函数的格式: int puts(char *str);
#include <stdio.h>
int main() {
char c[20];
gets(c);//gets中放入我们字符数组的数组名即可
puts(c);//puts等价于printf("%s\n",c);puts内放的参数是字符数组名
return 0;
}
str系列字符串操作函数
#include <stdio.h>
#include <string.h>
int mystrlen(char c[]){
int i = 0;
while(c[i]){//找到结束符后,循环结束,从而得出字符串长度
i++;
}
return i;
}
int main() {
char c[20];
int len;
char d[100] = "worls";
char e[100];
gets(c);
puts(c);
len = strlen(c);//统计字符串的长度
printf("len = %d\n",len);
len = mystrlen(c);
printf("my len = %d\n",len);
strcat(c,d);//把d中的字符串拼接到c中
puts(c);
strcpy(e,c);//把c中的字符串复制到e中
puts(e);
//c>“hello",返回值是正值;相等就是0;c<"hello",返回负值
printf("c?d=%d\n", strcmp(c,"hello"));
return 0;
}