您的位置:首页 > 其它

[TwistedFate]高级指针

2015-10-20 19:32 357 查看
需求:

1.创建一个学生类

2.声明一个结构体 成员变量:名字 性别 年龄 分数

typedef struct student{
char name[20];
char sex;
int age;
float score;
}Student;


1.结构体指针:指向结构体的指针

Student stu1 = {"zed",'m',28,98.0};
Student *p = &stu1;
printf("%s\n",stu1.name);
// (*p).name
// *p取出指针所指向的空间保存的值
printf("%s\n",(*p).name);
// 结构体指针当中 经常使用->指向符
printf("%s\n",p->name);


需求:编写函数 打印所有的成员变量


void printStudent(Student *stu)
{
printf("%s %c %d %.2f",stu->name, stu->sex, sti->age, stu->score);
}


`printStudent(p);`


printf("%p\n",p);
printf("%p\n",&stu1);
printf("%p\n",p->name);
// 结构体指针指向结构变量 相当于指向结构变量的第一个成员变量


// 练习1:定义一个点结构体,编写函数利用指针打印两点间的距离

typedef struct CPoint{
float x;
float y;
}CPoint;


void printDis(CPoint *point1, CPoint *point2)
{
float a = point1->x - point2->x;
float b = point1->y - point2->y;
float dis = sqrtf(a * a + b * b);
printf("Distance = %.2f",dis);
}


CPoint m = {3.0, 4.0};
CPoint n = {6.0, 8.0};
CPoint *p1 = &m;
CPoint *p2 = &n;
printDis(p1,p2);


// 练习2:编写一个函数,将学生名字首字母大写,空格改成下划线

void alterName(Student *stu)
{
int i = 0;
while(stu->name[i] != 0){
if(stu->name[i] ==' ')
stu->name[i] = ' ';
i++;
}
stu->name[0] = p->name[0] + 'A' - 'a';
printStudent(stu);
}


Student stu2 = {"c  bb ar", 'm', 15, 88.0};
Student *p = &stu2;
alterName(p);


// 声明三个结构体变量

Student stu3 = {"king", 'm', 60, 120.0};
Student stu4 = {"mx", 'm', 23, 50.0};
Student stu5 = {"tt", 'm', 54, 90.0};
Student *p = &stu3;
printf("%p\n",p);
// 结构体指针 地址+1 相当于加了整个结构体的字节数
printf("%p\n",p + 1);
// 声明一个结构体数组保存三个学生
Student stus[3] = {stu3, stu4, stu5};
Stundet *p = stus;
printf("%p\n",p);
// 结构体指针 指向结构体数组 就相当于 指向结构体数组的首元素
printrf("%p\n",&stus[0]);
// 如何利用指针 取出数组中的元素*(p + 1)
// (*(p + 1)).name
printf("%s\n",(*(p + 1)).name);
printf("%s\n"),(p + 1)->name);


// 练习3:编写函数 利用指针打印 结构体数组所有元素

void printStudentArray(Stundet *stus, int count)
{
for(int i = 0; i < count; i++)
{
printStudent(stus + i);
}
}


2.预编译指令

宏定义:

1.预编译时进行替换(编译前)

2.替换的过程

带参数宏定义: 参数使用什么名字 后面使用参 数的时候名字要一致

命名规范:

1.以小写k开头 后面驼峰 编写宏定义

2.全部大写

一般宏定义的参数 都已大写来写

#define kMaxValue(A,B) ((A) > (B) ? (A) : (B))


// 加括号是为了防⽌受操作符优先级的影响

条件编译:

作⽤:按不同的条件,编译不同的代码。

条件编译 有三种形式。

(1)

#ifdef WL

printf("WL已经定义了");

#else

#endif


(2)

#ifndef

#else

#endif


// 作用与第一种相反

(3)

#if(常量表达式)

代码段1

#else

代码段2

#endif


// 如果 常量表达式结果⾮0 编译器编译代码段1,否则编译代码段2。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: