quick
一般使用typedef来定义
typedef struct tagPoint
{
double x;
double y;
double z;
} Point;
参考:http://c.biancheng.net/view/298.html
基础
- 结构体也是基础类型,它是值传递,非引用传递,在作为传参时尽量使用指针,不然形参拷贝会浪费空间
- 直接调结构体变量是没有意义的,区别于数组变量是代表了数组的首元素地址
定义
可以在main函数外定义,可也以在main函数内定义
在main之外定义
# include <stdio.h>//引用函数库
# include <stdlib.h>
struct info{
char name[20];
int age;
};
struct info info1;
void main(){
info1.age=19;
sprintf(info1.name,"xiaowang");//(stdio.h),第一种初始化字符串方法
//strcpy(info1.name,"xiaowang");//(string.h),第二种初始化字符串方法
printf("%s %d",info1.name,info1.age);
}
在main内定义
# include <stdio.h>//引用函数库
# include <stdlib.h>
struct info{
char name[20];
int age;
};
void main(){
struct info info1;
info1.age=19;
sprintf(info1.name,"xiaowang");//(stdio.h),第一种初始化字符串方法
//strcpy(info1.name,"xiaowang");//(string.h),第二种初始化字符串方法
printf("%s %d",info1.name,info1.age);
}
声明结构体的时候直接定义
# include <stdio.h>//引用函数库
# include <stdlib.h>
struct info{
char name[20];
int age;
}info1,info2;
void main(){
struct info info1;
info1.age=18;
sprintf(info1.name,"xiaowang");//(stdio.h),第一种初始化字符串方法
//strcpy(info1.name,"xiaowang");//(string.h),第二种初始化字符串方法
printf("%s %d",info1.name,info1.age);
}
初始化结构体变量
单个参量初始化
参考结构体定义
结构体变量整体初始化
结构体变量不能整体引用,只能一个一个访问,赋值的时候才能用大括号一起赋值
# include <stdio.h>//引用函数库
# include <stdlib.h>
struct info{
char name[20];
int age;
};
void main(){
struct info info1={"xiaowang",18};
printf("%s %d",info1.name,info1.age);
}
匿名结构体
# include <stdio.h>//引用函数库
# include <stdlib.h>
struct
{
char name[20];
int age;
}info1={"xiaowang",17};//匿名结构体变量初始化只能紧跟结构体定义
void main(){
printf("%s %d",info1.name,info1.age);
}
嵌套结构体
struct info{
char name[20];
int age;
struct info_inner{//再次定义的结构体的变量会被当成母体的变量
//这个结构体不能在上层结构体内直接引用
int score;
int height;
};
};
等价于
struct info{
char name[20];
int age;
int score;
int height;
};
嵌套结构体应用
# include <stdio.h>//引用函数库
# include <stdlib.h>
struct info{
char name[20];
int age;
struct info_inner{//再次定义的结构体的变量会被当成母体的变量
//这个结构体不能在上层结构体内直接引用
int score;
int height;
}student1;//内部定义的第一种方式
struct info_inner student2;//内部定义的第二种方式
};
void main(){
struct info class;
class.student1.score = 99;
printf("%d\n",class.student1.score);
class.student2.score = 98;
printf("%d",class.student2.score);
}