数组传递【变量传递给子数组】
在指针阶段,会演示整型,浮点型,字符型传递给子数组
字符数组的传递
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
void print(char c[]);
/* 函数调用即赋值:实参传递给形参 */
void print(char d[]) {
int i = 0;
//d[i] != '\0',不需要给 print传递数组长度,因为 char arr[x]以 "\0" 结尾
//d[i] != 0
while (d[i]) {
printf("%c", d[i]);
i++;
}
printf("\n");
}
int main() {
char c[6] = "hello";
print(c); /* 我们称 c 为实参,调用 print() 函数时,把 c 赋值给 d,即 d = c */
return 0;
}
复习数组访问越界
code
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
void print(char c[]);
/* 函数调用即赋值:实参传递给形参 */
void print(char d[]) {
int i = 0;
//d[i] != '\0',不需要给 print传递数组长度,因为 char arr[x]以 "\0" 结尾
//d[i] != 0
while (d[i]) {
printf("%c", d[i]);
i++;
}
printf("\n");
}
int main() {
char c[5] = "hello";
print(c); /* 我们称 c 为实参,调用 print() 函数时,把 c 赋值给 d,即 d = c */
return 0;
}
gets()函数
需求分析
scanf() 函数通过 %s 读取输入的字符串,但是遇到空格就会停止读取,怎么样能够将空格视为字符,也读取并且填入字符串数组呢?
c 是一个字符数组,但是编译器给 c 内部存储了一个值, c 里面存储的值,其类型就是一个字符指针
可用替代
fgets(c, sizeof(c), stdin)
读取原理
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main() {
/* 字符数组的 数组名 内存储的就是 字符数组的起始位置 */
char c[20];
/* 自动将标记输入结束的换行符换成 "\0" */
gets(c);
printf("%s\n", c);
puts(c); /*等价于 printf("%s\n", c);*/
return 0;
}
strcpy()函数
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char c[10] = "Bye";
char d[10];
printf("字符串长度为 %d. \n", strlen(c));
strcpy(d, c);
/* 将数组元素从 c 拷贝到 d */
printf("拷贝完成之后,字符数组d的遍历.\n");
puts(d);
return 0;
}
使用 strcpy()拷贝字符常量
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char c[10] = "Bye";
char d[30];
printf("字符串长度为 %d. \n", strlen(c));
strcpy(d, "可以拷贝字符常量"); /* 形式参数有 const 修饰,可以传入常量 */
/* 将数组元素从 c 拷贝到 d */
printf("拷贝完成之后,字符数组d的遍历.\n");
puts(d);
return 0;
}
strcmp()函数
两个字符常量完全一样,函数返回值为1
字符串常量不同,且第一个参数首先出现 ascⅡ码值较大的情况,输出为 1
strcat()字符串拼接,用于追加的字符数组必须大于等于原始数组长度之和
指针
指针的本质
取地址与取值
& 为取地址运算符,也称引用;
*取值运算符,也称解引用;
两种运算符的优先级相同;
指针变量的声明
int *a, *b, *c;
直接访问与间接访问
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* 指针的本质就是存储地址 */
int main() {
int i = 5;
int* p = &i; /* 指针类型的变量如何赋予初值? */
printf("%d\n", i); /* 直接访问 */
printf("*p = %d\n", *p); /* 通过解引用,读取指针指向的变量的值 */
return 0;
}