结构体变量的定义和初始化//结构体变量的简单使用
/*结构体相关知识:
1.数组和结构体的区别在于是否保存相同类型的数据。*/
//结构体变量的定义和初始化
#include<stdio.h>
//结构体变量的定义和初始化
struct stu{
int id;
char name[32];
char sex;
int age;
}zhangsan,lisi = {1002,"李四",'B',25};//结构体变量
//使用typedef对结构体类型取别名
typedet struct{
int a;
int b;
char c;
} MSG;
int main(){//定义完结构体类型变量完再定义变量。
struct stu wangwu;
struct stu zhaoliu = {1001,"赵六",'B',20};
MSG msg1,msg2 = {100, 200, 'w'};//注意:typedef在的时候无法同时定义结构体变量。
return 0;
}
结构体变量的简单使用
#include <stdio.h>
#include <string.h>
struct stu{
int id;
char name[32];
char sex;
int age;
}zhangsan,lisi = {1002, "李四", 'B',25};//易错点:结构体变量写在;之前。
typedef struct{
int a;
int b;
char c;
}MSG;
int main(){
struct stu wangwu;
struct stu zhaoliu = {1001,"赵六",'B',20};
MSG msg1,msg2 = {100,200,'w'};
//结构体变量的使用
zhangsan.id = 1001;
strcpy(zhangsan.name,"张三");
zhangsan.sex = 'B';
zhangsan.age = 18;
printf("%d - %s - %c - %d\n",zhangsan.id,zhangsan.name,\
zhangsan.sex,zhangsan.age);
printf("%d - %s - %c - %d\n",zhaoliu.id,zhaoliu.name,\
zhaoliu.sex,zhaoliu.age);
printf("%d - %d - %c\n",msg2.a,msg2.b,msg2.c);
return 0;
}
结构体中嵌套结构体
#include <stdio.h>
#include <string.h>
typedef struct{
int year;//不许赋值,因为这是在定义类型
int mouth;
int day;
}BD;
typedef struct{
int id;
char name[5];//一个汉字占2个字节,加一个\0。两个汉字占4个字节,加一个\0。
BD birthday;
}STU;
int main(){
STU xiaoming;
xiaoming.id = 1001;
strcpy(xiaoming.name,"小明");
//如果结构体有嵌套结构体,赋值时找到最内层的成员再进行赋值。
xiaoming.birthday.year = 2002;
xiaoming.birthday.mouth = 12;
xiaoming.birthday.day = 20;
printf("%d -%s - %d-%d-%d\n",xiaoming.id,xiaoming.name,\
xiaoming.birthday.year,xiaoming.birthday.mouth,\
xiaoming.birthday.day);
//嵌套的形式定义并初始化
STU xiaoli = {1002,"小丽",2000,1,1};
printf("%d -%s - %d-%d-%d\n",xiaoli.id,xiaoli.name,\
xiaoli.birthday.year,xiaoli.birthday.mouth,\
xiaoli.birthday.day);
}
结构体数组元素的引用
#include <stdio.h>
typedef struct{
int num;
char name[20];
float score;
}STU;
int main(){
//定义一个结构体数组
STU edu[3] = {
{101,"Lucy",78},
{102,"Bob",59.5},
{103,"Tom",85}
};
//输出结构体数组中的元素
int j;
for(j = 0;j < 3; j++){
printf("%d - %s - %.2f\n",edu[j].num,edu[j].name,\
edu[j].score);
}
int i;
float sum = 0;
for(i = 0; i < 3; i ++){
sum += edu[i].score;
}
printf("平均成绩为%.2f\n",sum/3);
return 0;
}
结构体指针变量的定义方法:struct 结构体类型名 *结构体指针变量结构体指针变量对成员的引用:结构体指针变量名->成员
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct stu{
int id;
char name[32];
char sex;
int age;
};
int main(){
//定义一个结构体指针变量
struct stu *s;
//注意:结构体指针变量没办法直接控制上面的元素
//在堆区开辟结构体空间并将地址保存在结构体指针变量中
s= (struct stu *) malloc(sizeof(struct stu));//此为强制类型转换
s -> id = 1001;
strcpy (s -> name,"张三");//注意字符串用strcpy
s -> sex = 'B';
s -> age = 20;
printf("%d - %s - %c -%d\n",s -> id,s -> name,s -> sex,s ->age);
return 0;
}