介绍
指针:是存放某种特定变量的特定地址
字符:单引号内的字符,占八位。
字符串:多个字符加一个结束符’\0’组成。但其本质是一个指向第一个字符的指针。
小实验1
任务:判断“hello world!”中有多少个o。
代码如下:
#include<stdio.h>
char str[]="hello world!";
char *p;
int i,temp,sum;
void main()
{
//由于字符串本质是指针,故可以直接赋值,但注意此时p拿到的仅仅是str中第一个字符的地址。
p=str;
temp=sizeof(str);
for(i=0;i<temp;i++)
{
if('o'==*(p+i)){sum+=1;}
}
printf("%d\n",sum);
}
运行结果:sum==2
错误操作:
char *p;
p='A'; //字符不是指针,无法直接赋值给指针
小实验2
任务:用一个结构体,其成员包括名字和分数。如name:Xiao Ming,score:85
代码如下:
#include<stdio.h>
char str[20];
void main()
{
struct{
char *name;
int score;
}student;
//从键盘读取输入
printf("please enter the name:");
gets(str); //从键盘读取字符串
student.name=str; //字符串赋值给指针
printf("please enter the score:");
scanf("%d",&student.score);
//最终结果显示
printf("Name: %s\nScore: %d\n",student.name,student.score);
}
结果:
在单片机中的应用
任务:在oled中,某个特定的位置显示一个字母。
代码如下:
char *p;
p="A";
Display_Number(3,8,*p); //我自己编写的oled驱动函数,不可以直接套用。其中三个参数分别是行、列、ascll码
结果: