结构的定义与基本操作

在C语言中,定义结构变量时,结构类型名前必须加struct。

可以省略结构名称,但不能省略变量名。

\\指向结构变量的指针

#include<stdio.h>

int main()
{
struct xm
{
    int Math;
    int Chinese;
    int English;
}xm1={100,100,100};
struct xm *p;
p=&xm1;
printf("%d %d %d\n",xm1.Math,xm1.Chinese,xm1.English);
printf("%d %d %d\n",(*p).Math,(*p).Chinese,(*p).English);
printf("%d %d %d\n",p->Math,p->Chinese,p->English);
return 0;
}


\\用指向结构的指针做函数参量
#include<stdio.h>
struct my
{
    int Chinese;
    int Math;
    int English;
} score= {100,100,100};
void print1(struct my grade)
{
    printf("%d %d %d\n",grade.Chinese,grade.Math,grade.English);
}
void print2(struct my *p)
{
    printf("%d %d %d\n",p->Chinese,p->Math,p->English);
}
int main()
{
    void print1(struct my grade);
    print1(score);

    void print2(struct my *p);
    print2(&score);

    return 0;
}

\\结构类型的嵌套
#include<stdio.h>
struct subject
{
    int Math;
    int Chinese;
    int English;
};
struct person
{
    char Name[10];
    long tel;
    struct subject score;
}stu1={"xm",123456,100,100,100};
int main()
{
    printf("%s\n",(&stu1)->Name);
    printf("%ld\n",stu1.tel);
    printf("%d\n",(&stu1)->score.Math);
    printf("%d\n",stu1.score.Chinese);
    printf("%d\n",stu1.score.English);
    return 0;
}

//typedef的用法
#include<stdio.h>
int main()
{
typedef struct node//node是结构体的一个名称,可有可无.
{
    int Math;
    int Chinese;
    int English;
}linknode,*sqlink;//新的结构类型
 linknode xm={100,100,100};
 sqlink p;
p=&xm;
printf("%d %d %d\n",xm.Math,xm.Chinese,xm.English);
printf("%d %d %d\n",(*p).Math,(*p).Chinese,(*p).English);
printf("%d %d %d\n",p->Math,p->Chinese,p->English);
return 0;
}

猜你喜欢

转载自blog.csdn.net/mycsdn_xm/article/details/80672882