今天给大家分享C语言中结构体的几种常见使用方法,包括基础结构体定义与初始化,结构体指针的两种访问方式,结构体数组的遍历,动态内存分配与结构体使用,typedef简化结构体类型
基础结构体定义与使用
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>;// 定义一个学生结构体
struct student {char name[20]; // 姓名int num; // 学号float score; // 分数
};int main()
{// 结构体变量初始化struct student s1 = {"zhangsan",10001,99.21};// 打印结构体成员printf("%s\n %d\n %.2f\n", s1.name, s1.num, s1.score);// 声明结构体变量struct student s2;// 从输入获取结构体成员值scanf("%s %d %f",&s2.name,&s2.num,&s2.score); //.2的格式不能用在scanf里面 printf("%s\n %d\n %.2f\n", s2.name, s2.num, s2.score);// 结构体数组struct student sarr1[3];scanf("%s %d %f", &sarr1[0].name, &sarr1[0].num, &sarr1[0].score);printf("%s\n%d\n%.2f\n", sarr1[0].name, sarr1[0].num, sarr1[0].score);return 0;
}
结构体指针操作
struct student {char name[20]; // 姓名int id; // 学号float score; // 分数
};int main()
{struct student s1 = { "wangwu",10086,99.98 };// 定义结构体指针并指向s1struct student* ps1 = &s1;// 通过指针访问结构体成员 - 方法1printf("%-s ,%-d ,%-.2f\n", (*ps1).name, (*ps1).id, (*ps1).score);// 通过指针访问结构体成员 - 方法2(更常用)printf("%-s ,%-d ,%-.2f", ps1->name,ps1->id,ps1->score);return 0;
}
结构体数组与指针遍历
struct student {char name[20]; // 姓名int id; // 学号float score; // 分数
};int main()
{// 初始化三个学生结构体struct student s1 = { "zhangsan",10086,88.9 };struct student s2 = { "lisi",10087,98.9 };struct student s3 = { "wangwu",10088,89.9 };// 结构体数组初始化struct student arr1[3] = { s1,s2,s3 };// 结构体指针指向数组首地址struct student* p = arr1;int i = 0;// 遍历结构体数组for (i = 0; i < 3; i++){printf("%-s\n%-d\n%-.2f\n", p[i].name, p[i].id, p[i].score);}return 0;
}
动态内存分配与结构体
struct student {char name[20]; // 姓名int id; // 学号float score; // 分数
};int main()
{// 声明结构体指针struct student* ps1;// 动态分配内存ps1 = malloc(sizeof(struct student));// 赋值操作strcpy(ps1->name,"wangdao"); // 字符串赋值需要使用strcpyps1->id = 1235;ps1->score = 99.86;printf("%-s ,%-d ,%-.2f", ps1->name, ps1->id, ps1->score);return 0;
}
使用typedef简化结构体
// 使用typedef定义结构体别名
typedef struct student {char name[20]; // 姓名int id; // 学号float score; // 分数
}stu,*pstu; // stu == struct student; pstu == struct student *; int main()
{// 使用别名声明变量stu s1 = { "wangwu",10081, 90.81 };pstu p1 = &s1; // p1是指向stu类型的指针return 0;
}// typedef也可以用于基本数据类型
typedef int INTEGER; // 将int定义为INTEGER
int main()
{INTEGER num = 0; // 等同于int num = 0;printf("%d\n", num);return 0;
}