结构体定义与使用
struct Dog{
char name[10];
int age;
char sex;
};
int main(){
struct Dog dog;
strcpy(dog.name,"旺财");
dog.age = 3;
dag.sex = 'G';
printf("name:%s,age:%d,sex:%c \n",dog,name,dog.age,dog.sex);
return 0;
}
struct Person{
char * name;
int age;
char sex;
}ppp = {"abc",33,'M'}
ppp2,
ppp3,
ppp4
;
int main(){
printf("name:%s,age:%d,sex:%c \n",ppp ,name,ppp.age,ppp.sex);
ppp3.name = "adcd";
ppp4.age = 3;
ppp4.sex = 'G';
printf("name:%s,age:%d,sex:%c\n",ppp4,name,ppp4.age,ppp4.sex);
return 0;
}
struct Study{
char * studyContext;
};
struct Student{
char name[10];
int age;
char sex;
struct Study study;
struct Wan{
char * wanContext;
} wan;
};
int main(){
struct Student student = {"李元霸",88,'m',
{"学习c"},
{"王者荣耀"}
};
printf("name:%s,age:%d,sex:%c,study:%s,wan:%s \n",student,name,
student.age,student.sex,student.sudyu.studyConent,student.wan.wanContent);
return 0;
}
结构体指针与动态内存开辟
struct Cat{
char name[10];
int age;
};
int main(){
struct Cat cat = {"小花猫",2};
struct Cat * carp = &cat;
catp->age = 3;
strcpy(catp->name,"小花猫2");
printf("name:%s,age:%d \n",catp->name,catp->age);
return 0;
}
struct Cat{
char name[10];
int age;
};
int main(){
struct Cat * cat = malloc(sizeof(strcut Cat));
strcpy(cat->name,"金色猫");
cat->age = 5;
printf("name:%s,age:%d \n",cat->name,cat->age);
if(cat){
free(cat);
cat = NULL;
}
return 0;
}
结构体数组
struct Cat{
char name[10];
int age;
};
int main(){
strcut Cat cat[10]={
{"abcd",1}
{}
{}
{}
{}
{}
{}
{}
{}
{}
};
struct Cat cat9 = {"小花猫9",9};
cat[9] = cat9;
printf("name:%s,age:%d \n",cat9->name,cat9->age);
struct Cat * cat2 = malloc(sizeof (struct cat) * 10);
strcpy(cat2->name,"adfa");
cat2.age = 1;
printf("name:%s,age:%d \n",cat2->name,cat2->age);
cat2+=7;
strcpy(cat2->name,"adfa");
cat2.age = 1;
printf("name:%s,age:%d \n",cat2->name,cat2->age);
return 0;
}
结构体与结构体指针取别名
struct Workder_{
char name[10];
int age;
char sex;
};
typedef struct Workder_;
typedef Workder_ * workder;
typedef struct{
char name[10];
int age;
char sex;
} AV;
enum CommentType {
TEXT = 10,
TEXT_IMAGE,
IMAGE
};
int main(){
Workder worker = malloc(sizeof(workder_));
struct Workder_ workder1 = malloc(sizeof (struct Workder_));
Workder_ workder2 = malloc(sizeof (Workder_));
AV av = {};
AV * avp = malloc(sizeof (AV));
enum CommentType commentType = TEXT;
CommentType commentType = TEXT;
return 0;
}