1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > C语言结构体变量 指针以及对结构体成员的访问

C语言结构体变量 指针以及对结构体成员的访问

时间:2023-04-18 03:47:09

相关推荐

C语言结构体变量 指针以及对结构体成员的访问

文章目录

结构体结构体变量访问成员的方法结构体指针变量访问成员的方法

结构体

struct AGE{int year;int month;int day;};struct STUDENT{char name[20]; //姓名int num; //学号struct AGE birthday; //生日float score; //分数};

结构体变量访问成员的方法

int main(void){struct STUDENT student1; /*用struct STUDENT结构体类型定义结构体变量student1*/student1.birthday.year = 1989;student1.birthday.month = 3;student1.birthday.day = 29;student1.num = 1207041;student1.score = 100;return 0;}

访问方式:

结构体变量.成员名

结构体指针变量访问成员的方法

int main(void){struct STUDENT student1; /*用struct STUDENT结构体类型定义结构体变量student1*/struct STUDENT *p = NULL; /*定义一个指向struct STUDENT结构体类型的指针变量p*/p = &student1; /*p指向结构体变量student1的首地址, 即第一个成员的地址*/strcpy((*p).name, "小明"); //(*p).name等价于student1.name(*p).birthday.year = 1989;(*p).birthday.month = 3;(*p).birthday.day = 29;(*p).num = 1207041;(*p).score = 100;printf("name : %s\n", (*p).name); //(*p).name不能写成pprintf("birthday : %d-%d-%d\n", (*p).birthday.year, (*p).birthday.month, (*p).birthday.day);printf("num : %d\n", (*p).num);printf("score : %.1f\n", (*p).score);return 0;}

我们看到,用指针引用结构体变量成员的方式是:

(*指针变量名).成员名

括号使用是因为优先级问题。

此外为了使用的方便和直观,用指针引用结构体变量成员的方式:

(*指针变量名).成员名

可以直接用:

指针变量名->成员名

来代替,它们是等价的。->是“指向结构体成员运算符”,它的优先级同结构体成员运算符“.”一样高。p->num的含义是:指针变量 p 所指向的结构体变量中的 num 成员。p->num最终代表的就是 num 这个成员中的内容。

int main(void){struct STUDENT student1; /*用struct STUDENT结构体类型定义结构体变量student1*/struct STUDENT *p = NULL; /*定义struct STUDENT结构体类型的指针变量p*/p = &student1; /*p指向结构体变量student1的首地址, 即第一项的地址*/strcpy(p->name, "小明");p->birthday.year = 1989;p->birthday.month = 3;p->birthday.day = 29;p->num = 1207041;p->score = 100;printf("name : %s\n", p->name); //p->name不能写成pprintf("birthday : %d-%d-%d\n", p->birthday.year, p->birthday.month, p->birthday.day);printf("num : %d\n", p->num);printf("score : %.1f\n", p->score);return 0;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。