结构体的梳理与运用
结构体
struct 结构名称{
//使用数据类型定义变量
};//要有分号
结构体通常用于抽象一类事物的共同特征,用数据类型描述
结构体的创建方式(3)
- 最常规的方式
struct book{
int price;
char author;
};
- 缺省的写法
struct {
int price;
char author;
}book;
无结构体名,只有唯一一个名为book的全局结构体变量
- 结构体typedef创建
typedef struct book{
int price;
char author;
}book1,book2[3],*book3;
//book1为结构体变量的别名
//book2[3]为结构体体数组的别名
//*book3为结构体指针别名
结构体后面的全为别名
若除去typedef 则结构体后的book1,book2[3],*book3为变量
新建结构体变量(2)
#include <stdio.h>
struct book{
int price;
char author;
}book1;//<=定义book
struct book book2;//<=定义全局变量book2
int main{
struct book book3;//<=定义book3
return 0;
}
结构体初始化
结构体初始化应该注意的内容:
1.数据带上大括号
2.在初始化时,一定要与结构体定义的数据类型相同
struct Data{
char first [20];
int sceond;
float third;
double fourth;
};
struct Data data={"first",2,2.3,2.333};
//不存在先创建在初始化
//struct Data data;
//data={"first",2,2.3,2.333};(错误写法)
结构体中的数据访问
!!!结构体变量只能用结构体(结构体指针,普通结构体变量)访问
-
普通结构体用.直接访问:结构体名称.成员名
-
结构体指针用->访问:结构体指针->成员
#include <stdio.h> #include <string.h> struct Data{ char first [20]; int sceond; float third; }; int main() { struct Data data; strpry(data.first,"First"); data.third=2.1; data.second=2;//无需按照顺序 printf("%s\t%d\t%f\n ",data.first, data.second,data.third); struct Data P=&data; p->second=22; p->third=4.55; printf("%s\t%d\t%f\n ",p->first, p->second,p->third); printf("%s\t%d\t%f\n ",(*p).first, (*p).second,(*p).third);//解引用同样可以达到相同效果 //结构体中字符串的赋值只能用拷贝,数组的赋值只能用循环 return 0; } -
通过堆内存申请,用指针操作
struct Data *Pdata=(struct Data*)malloc(sizeof(Data)); free(Pdata);//应释放内存Pdata等效为一个结构体变量
结构体充当返回值
用数据封装给结构体,充当返回值,一次可以返回多个变量。
struct Data{
int i;
int j;
};
struct Data assign(){
struct Data data;
data.i=1;
data.j=2;
return data;
}
通过指针表示变量写法
struct book{
int price;
char author;
};
struct Book* create(int a;char b){
struct Book *book=(struct Book*)malloc(sizeof(Book));
book->price=a;
strcpy(book->author,b);
return book;
}
int main()
{
struct Book* p=create(20;Dickens);
printf("%d\t%s\n",p->price,p->author)
free(p);
p=NULL;//将指针指向NULL
return 0;
}
结构体数组的访问
struct Student{
char name[20];
int age;
int num;
int score[3];
};
void PrintInfo(struct Student stu[],int len){
printf("姓名\t年龄\t学号\语文\t数学\t英语\n");
for(int i=0;i<len;i++){
printf("%s\t%d\t%d\t",stu[i].name,stu[i].age,(stu+i)->num);
for(int j=0;j<3;j++){
printf("%d\t",stu[i].score[j]);
}
printf("\n");
}
}
int main(){
struct Student stu[3]={
{"A",18,1,{60,65,67}},
{"Bb",19,2,{90,90,90}},
{"cc",19,3,{82,81,83}}
};
}
278

被折叠的 条评论
为什么被折叠?



