如果出现*,前面有类型修饰符,int,,,此时*p仅仅起到标示作用,告诉编译器时指针。有*p出现没有修饰符,*p代表取值操作,会把指针指向的区域内容读出2: 获取数组的地址
struct student stu[5] = {...};
用指针获取数组的首地址有两种方法:
2.1 struct student *pointer = stu;
2.2 struct student *pointer = &stu[0];
3 :函数调用
例如一个函数 int echange(int *a,int *b);
则在改函数调用的时候 :
int a = 1,b=2;
ehang(&a,&b);-----------------------在调用的时候一定不要忘记取地址符号“&”
例如 一个函数 int exchang(struct student *pointer)
如果时这种情况如下
struct student *pointer = ArrayName 等价于 struct student *pointer = &ArrayName[0];
exchang(pointer);
**************作业2*******************
使用指针 查找学院数组中 性别为男 的学员,成绩加10分,超过100分的计为100分
解题如下:
解析:这题就需要首先定义一个结构体student,并且在程序入口处就要定义,有多少个学生。当然就是结构体数组了,这个数组的个数就是多少学生了。
此题假设有5个学生。用指针获完成该题。
首先把工程完成,我们在来说说这些函数的用法。
首先在.h文件中定义结构题 student 和一个初始化方法。
在.m中实现这个事咧方法。
#import "student.h"
//初始化结构体变量的值
/**
此处传过来一个student结构体指针,用来给结构体初始化值,在调用该函数的时候用取地址符号(&)
*/
void InitStudent(structstudents *sender)
{
/**尖头是取值 */
sender->male =0;
sender->score =0.0f;
}
/**
用一个int类型来初始化该结构体赋值为0
*/
void InitStudentLine(structstudents *stu,int count)
{
for (int index =0; index < count; index++) {
InitStudent(stu+1);
}
}
void SetStudentMale(structstudents *sender,int male)
{
sender->male = male;
}
void SetStudentMaleCount(structstudents *stu,int count)
{
for (int index =0; index < count; index++) {
int male = index %2 ==0 ?1:2;
SetStudentMale(&stu[index], male);
//(stu+1)->male = male;
}
}
void SetStudentScore(structstudents *stu)
{
int res =arc4random() % (100 -60 +1) +60;
float str =arc4random() %1000/10000.0f;
stu->score = res + str;
}
void SetStudentScoreCount(structstudents *stu,int count)
{
for (int index =0; index < count; index++) {
SetStudentScore(&stu[index]);
}
}
在main。m中的程序如下
//定义一个结构体5个元素
struct students stuValue[5];
/**
此处切忌:我个人理解,此处取虽然取的是stuvalue的首地址,但是同样会往后累加5个元素的地址。
也可换一种取地址操作
struct students *stuPointer = &stuValue[0];
*/
structstudents *stuPointer = stuValue;
//初始化函数
/**
此处同样可换一种方法写:InitStudentLine(stuValue, 5);
*/
InitStudentLine(&stuValue[0],5);
//加载数据
//加载性别:同上还有另外一个写法
SetStudentMaleCount(stuPointer,5);
//加载分数:同上还有另外一个写法
SetStudentScoreCount(stuPointer,5);
for (int index =0; index <5; index++) {
float sco = (&stuPointer[index])->score;
printf("-----------------分数:%.2f---性别:%d\n\n",sco,(&stuPointer[index])->male);
//判断是否为男性
if ((&stuPointer[index])->male ==1) {
sco += 10.0f;
}
printf("加分后的分数:%.2f\n",sco >100.0f ?100.0f:sco);
}
- 欢迎各位一块学习,提高逼格!
-
也可以添加洲洲哥的微信公众号
更多消息
更多信iOS开发信息 请以关注洲洲哥 的微信公众号,不定期有干货推送: