c语言-----结构体

结构体:一个用同一名字引用的变量集合体,提供了将相关信息组合在一起的手段。

一:结构体变量的定义及初始化

①定义:

(1)在定义结构体类型后再定义结构体变量
struct student
{
    char name[10];//成员项
    int score[3];
    float aver;
};
struct sutdent stu1,stu2//在定义结构体类型后再定义结构体变量

(2)定义结构体类型同时定义结构体变量

struct student
{
    char name[10];//成员项
    int score[3];
    float aver;
}stu1,stu2;

(2)直接定义结构体变量

struct 
{
    char name[10];//成员项
    int score[3];
    float aver;
}stu1,stu2;

②初始化

struct student
{
    char name[10];//成员项
    int score[3];
    float aver;
};
struct sutdent stu1={"changfan",{100,98,99},99},stu2={"luzhu",{100,100,100},100}

二:结构体变量的使用

①结构体成员的使用

#include<stdio.h>
#include<string.h>

//声明结构体类型 
struct student{
        char name[10];
        int sorce[3];
        float aver;
};

int main()
{
    struct student st1;
    strcpy(st1.name,"changfan");
    st1.sorce[0]=98;
    st1.sorce[1]=99;
    st1.sorce[2]=96;
    
    st1.aver=(st1.sorce[0] + st1.sorce[1] + st1.sorce[2])/3.0;    
    
    printf("%s\n",st1.name);
    printf("%d %d %d\n",st1.sorce[0],st1.sorce[1],st1.sorce[2]);
    printf("%f",st1.aver);
     
    return 0;
 } 

②结构体变量作为函数的参数

#include<stdio.h>

struct student{
    char name[10];
    int sorce[3];
    float aver;
};

int printstu(struct student st1)
{
    printf("name:%s;\nsocre[0]:%d,socre[1]:%d,socre[2]:%d;\naver:%f",
        st1.name,st1.sorce[0],st1.sorce[1],st1.sorce[2],st1.aver);

    return 0;
}

int main()
{
    
    struct student st1={"changfan",{99,98,96},96};
    printstu(st1);
    
    return 0;
}

三、结构体指针和数组

①结构体数组

#include<stdio.h>
#define N 5
struct student{
    char name[10];
    int sorce[3];
    float aver;
};
int main()
{
    struct student stu[N]; 
    int i,j;
    for(i=0;i<N;i++){
        printf("请输入第%d学生的姓名:",i+1);
//对结构体数据的读入时,字符类型可以没有取地址符(&) 
        scanf("%s",stu[i].name);
        for(j=0;j<3;j++){
            printf("请输入第%d学生的第%d门成绩:",i+1,j+1);
//对结构体数据的读入数据时,整形及浮点型必须包含数字 
            scanf("%d",&stu[i].sorce[j]);
        }
        stu[i].aver=(stu[i].sorce[1] + stu[i].sorce[2] + stu[i].sorce[0])/3.0;
    }
    
    for(i=0;i<N;i++){
        printf("%s %f\n",stu[i].name,stu[i].aver);
    }
    
    return 0;
}

②结构体指针

#include<stdio.h>
struct student
{
    char name[10];
    int score[3];
    float aver;
};

int main()
{
    struct student st,* p;
    p = &st;

//直接显示法读取数据 
    scanf("%s,%d,%d,%d,%d",(* p).name,&(* p).score[0],&(* p).score[1],
                        &(* p).score[2],&(* p).aver);
//采用指针特有结构体运算符->输出 
    printf("name:%s\nscore[0]=%dscore[1]=%dscore[2]=%d\naver=%d",
            p->name,p->score[0],p->score[1],p->score[2],p->aver); 
    
    return 0;
 } 

猜你喜欢

转载自www.cnblogs.com/changfan/p/11665169.html