初识一维数组:
#include <stdio.h>
#define N 5
/*
int 占4个字节
float 占4个字节
char 占1个字节
*/
//打印数组里的每一个元素,数组在传递时,元素个数传递不过去
void print(int b[], int len)
{
int i;
for (i = 0; i < len; i++) {
printf("a[%d] = %d\n", i, b[i]);
}
b[4] = 20;//在子函数中修改数组元素
}
int main()
{
/*一维数组的格式:类型说明符 数组名[常量表达式]
常量表达式可以是常量或符号常量,但不能是变量
定义数组就是写一个变量名,后面加上方括号,方括号内写上整型常量*/
//int a[10]= { 1,3,5,7,9 }; //内存中的数值分别为1,3,5,7,9,0,0,0,0,0
//int a[N];
/*要使一个数组中全部元素的值为0,可以写成*/
//int b[10] = { 0 };
int j = 10;
int a[5] = { 1,2,3,4,5 };
int i = 3;
//a[5] = 20; //访问越界,访问了不属于自己的空间
//a[6] = 21; //并且访问越界会导致数据异常
//a[7] = 22;
printf("j = %d\n", j);
print(a, 5);
printf("a[4] = %d\n", a[4]);
return 0;
}
字符数组:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//初始化字符数组时,一定要让字符数组的大小比看到的
//字符串长度多1位,多出来的1位存储\0结束符
int main()
{
char c[6] = { 'h','e','l','l','o'};
char d[4] = "how";
printf("%s----%s\n", c, d);//%s -->匹配字符串
char e[20],f[20];
scanf("%s%s", e,f); //scanf读取数组时不用取地址(即不用加&)
printf("%s-----%s\n", e, f);
}
字符数组的传递:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void print(char d[])
{
int i = 0;
while (d[i] != '\0')// while (d[i] != 0) // d[i]
{
printf("%c", d[i]);
i++;
}
printf("\n");
//修改字符数组中的字符串的内容,把首字母变成大写
d[0] = d[0] - 32;
}
int main()
{
char c[10] = "hello";
print(c);
printf("%s\n", c);
return 0;
}
gets与puts:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
/*
遇到一个问题,scanf通过%s读取字符串时,当遇到空格以后,就
会匹配结束,这样就没办法把一行带有空格的字符串存入一个字符
数组中,所以gets就应运而生
*/
int main()
{
char c[20];
//字符数组的数组名里存的就是字符
//数组的起始地址(字符指针类型)
/*
如何理解上面注释?如下:
char c[20];
c 是一个字符数组,但是编译器给c内部存了一个值,
c里边存储的值的类型是字符指针
*/
gets(c);//当一次读取一行时,使用gets,其括号内必须是字符数组,不能是整型数组
puts(c);//等价于printf("%s\n",c);
return 0;
}
str系列函数的使用:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
//str系列字符串操作函数主要包括strlen,strcpy,strcmp,strcat
//strlen 统计字符串长度
//strcpy 将某个字符串复制到字符数组中
//strcmp 比较两个字符串的大小
//strcat 将两个字符串拼接到一起
int main()
{
char c[20] = "hello";
printf("数组c内的字符串长度 = %d\n", strlen(c));
char d[20];
//char* strcpy(char* to, const char* from);
// 有const修饰代表这个地方可以放一个字符串常量
strcpy(d, "study");
puts(d);
/*strcpy(d, c);
puts(d);*/
//strcmp 比较的是两个字符串比较的是对应字符位置的Ascii码值
//int ret = strcmp("hello", "hello");
//printf("两个字符串比较后的结果为 = %d\n", ret);
printf("两个字符串比较后的结果为 = %d\n", strcmp("hello", "hello"));
printf("两个字符串比较后的结果为 = %d\n", strcmp("how", "hello"));
printf("两个字符串比较后的结果为 = %d\n", strcmp("hello", "how"));
//strcat 拼接两个字符串,注意的是目标数组要能够容纳拼接后的字符串
strcat(c, d);
puts(c);
return 0;
}
如有错误,请大神们多多指教,我会积极改正哒,谢谢!!!