1. 程式人生 > >結構體初始化 訪問的三種方式(結構體指標)

結構體初始化 訪問的三種方式(結構體指標)

輸出三個學生中成績最高的學生資訊

1> 

#include<stdio.h>
typedef struct student
{
    int num;
    char name[10];
    int score;


} Student;
int main()
{
    Student s1,s2,s3,max;
    scanf("%d %s %d",&s1.num,s1.name,&s1.score);
    scanf("%d %s %d",&s2.num,s2.name,&s2.score);
    scanf("%d %s %d",&s3.num,s3.name,&s3.score);
    max=s1;
    if(max.score<s2.score) max=s2;
    if(max.score<s3.score) max=s3;
    printf("%d %s %d",max.num,max.name,max.score);
}

2> 結構體指標;

#include<stdio.h>
typedef struct student
{
    int num;
    char name[10];
    int score;


} Student;
int main()
{
    Student s1,s2,s3,*p;//*p,結構體指標
    scanf("%d %s %d",&s1.num,s1.name,&s1.score);
    scanf("%d %s %d",&s2.num,s2.name,&s2.score);
    scanf("%d %s %d",&s3.num,s3.name,&s3.score);


    p=&s1;
    if(p->score<s2.score) p=&s2;
    if((*p).score<s3.score) p=&s3;//p->和(*p).相同;
    printf("%d %s %d",p->num,p->name,(*p).score);
}

訪問成員變數三種方式:s1.score,p->score,(*p).score;

結構體初始化

student s1={1001,lingming,98};

*p=NULL;