- 结构体先定义后调用,定义的时候不分配内存,创建时才分配内存
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<time.h> struct mycoach//mycoach是结构体类型,如果省略就是无名结构体 { //还可以包含其他结构体,其中每个元素的内存都相互独立 char name[30]; int age; }; void main() { struct mycoach cpc; sprintf(cpc.name,"陈培昌");//字符串不可以等号赋值,strcpy()---在string模块下 printf("\n%s",cpc.name); system("pause"); }
- 一次性可以声明多个
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<time.h> struct mycoach//mycoach是结构体类型,如果省略就是无名结构体 { //还可以包含其他结构体,其中每个元素的内存都相互独立 char name[30]; int age; char expertin[100]; }; void main() { struct mycoach cpc,xxd,wr,fgf; sprintf(cpc.name,"陈培昌");//字符串不可以等号赋值,strcpy()---在string模块下 printf("%s\n",cpc.name); system("pause"); }
- 宏取代
#define _CRT_SECURE_NO_WARNINGS #define jl struct mycoach #include<stdio.h> #include<stdlib.h> #include<time.h> struct mycoach//mycoach是结构体类型,如果省略就是无名结构体 { //还可以包含其他结构体,其中每个元素的内存都相互独立 char name[30]; int age; char expertin[100]; }; void main() { jl cpc,xxd,wr,fgf; sprintf(cpc.name,"陈培昌");//字符串不可以等号赋值,strcpy()---在string模块下 printf("%s\n",cpc.name); system("pause"); }
- 形式3
#define _CRT_SECURE_NO_WARNINGS #define jl struct mycoach #include<stdio.h> #include<stdlib.h> #include<time.h> struct mycoach//mycoach是结构体类型,如果省略就是无名结构体 { //还可以包含其他结构体,其中每个元素的内存都相互独立 char name[30]; int age; char expertin[100]; }cpc, xxd, wr, fgf;//定义时,就声明变量 void main() { sprintf(cpc.name,"陈培昌");//字符串不可以等号赋值,strcpy()---在string模块下 printf("%s\n",cpc.name); system("pause"); }
- 结构体类型和结构体变量的区别
结构体类型不分配内存,结构体变量分配,结构体类型不可以访问,赋值,存取,运算;成员名与类型名可以重名
- 初始化方法
#define _CRT_SECURE_NO_WARNINGS #define jl struct mycoach #include<stdio.h> #include<stdlib.h> #include<time.h> struct mycoach//mycoach是结构体类型,如果省略就是无名结构体 { //还可以包含其他结构体,其中每个元素的内存都相互独立 char name[30]; int age; char expertin[100]; }cpc, xxd, wr, fgf; void main() { struct mycoach cpc = {"陈培昌",22,"泰拳,散打"}; printf("%s\n", cpc.expertin); system("pause"); }
#define _CRT_SECURE_NO_WARNINGS #define jl struct mycoach #include<stdio.h> #include<stdlib.h> #include<time.h> struct mycoach//mycoach是结构体类型,如果省略就是无名结构体 { //还可以包含其他结构体,其中每个元素的内存都相互独立 char name[30]; int age; char expertin[100]; }cpc = { "陈培昌", 22, "泰拳,散打" }; void main() { printf("%s\n", cpc.expertin); system("pause"); }
- 无名结构体,无法访问,无法创建变量,但下列方法可以(业务场景,限量使用该结构体,如银行数据库的最高权限)
#define _CRT_SECURE_NO_WARNINGS #define jl struct mycoach #include<stdio.h> #include<stdlib.h> #include<time.h> struct { //还可以包含其他结构体,其中每个元素的内存都相互独立 char name[30]; int age; char expertin[100]; }cpc; void main() { sprintf(cpc.name,"陈培昌"); cpc.age = 22; sprintf(cpc.expertin,"泰拳,散打"); printf("%s\n", cpc.expertin); system("pause"); }
another form
#define _CRT_SECURE_NO_WARNINGS #define jl struct mycoach #include<stdio.h> #include<stdlib.h> #include<time.h> struct { //还可以包含其他结构体,其中每个元素的内存都相互独立 char name[30]; int age; char expertin[100]; }cpc = { "陈培昌", 22, "泰拳,散打" }; void main() { printf("%s\n", cpc.expertin); system("pause"); }