【C语言】结构体指针

来源:互联网 发布:淘宝店铺怎么复核认证 编辑:程序博客网 时间:2024/05/17 04:34

指向结构体对象的指针变量即可以指向结构体变量,也可指向结构体数组中的元素。指针变量的基类型必须与结构体变量的类型相同。
如:
struct Student *pt; //pt可以指向struct Student类型的变量或数组元素。

典例:
通过结构体变量的指针变量输出结构体变量成员中的成员的信息。
解题思路:
(1)怎样对结构体变量成员赋值
(2)怎样通过结构体变量的指针访问结构体变量中成员

#include<stdio.h>#include<windows.h>#include<string.h>int main(){    struct Student    {        long num;        char name[20];        char sex;        float score;    };    struct Student stu_1;    const struct Student *p;    p = &stu_1;    stu_1.num = 10101;    strcpy_s(stu_1.name,20, "Li Lin");  //用字符串复制函数给stu_1.name    stu_1.sex = 'M';    stu_1.score = 89.5;    printf("No:%ld\nname:%s\nsex:%c\nscore:%5.1f\n", stu_1.num, stu_1.name, stu_1.sex, stu_1.score);    printf("No:%ld\nname:%s\nsex:%c\nscore:%5.1f\n", (*p).num, (*p).name, (*p).sex, (*p).score);    system("pause");    return 0;}

说明:C语言允许把(*p).num用p->num来代替。

0 0