标签:
#include <stdio.h>
void structOne()
{
//定义一个名为Student的结构体类型
struct Student {
int age; //年龄
float score; //成绩
char *name; //名字
};
//定义结构体变量
struct Student stu={21,99.0,"Tom"};
//stu={22,88.0,"Jack"};---错误方法
printf("tom age is %d,score is %.2f,name is %s",stu.age,stu.score,stu.name);
struct Teacher {
int age; //年龄
float height; //身高
char *name; //名字
}tea1={33,180.2f,"Teacher Li"};
tea1.height=170.1;//结构体变量的某个结构成员重赋值
printf("\nteacher age is %d,height is %g,name is %s",tea1.age,tea1.height,tea1.name);
}
void structTwo()
{
//声明一个匿名的结构体
struct {
int age;
char *name;
}stu1={22,"Jack"},stu2=stu1;//声明结构体变量的时候,可以定义多个
printf("匿名结构体1:age:%d,name:%s\n",stu1.age,stu1.name);
printf("匿名结构体2:age:%d,name:%s\n",stu2.age,stu2.name);
}
#pragma mark 2 结构体嵌套调用
void structThree()
{
//结构体的递归(错误)
// struct Student {
// int age;
// char *name;
// struct Student stu1;
// };
//结构体的嵌套
struct Birthday{
int year;
int month;
int day;
};
struct Student {
int age;
char *name;
struct Birthday bir1;
};
struct Student stu1={21,"Jack",{1991,10,10}};
printf("age=%d,name=%s,birthday:%d-%d-%d",stu1.age,stu1.name,stu1.bir1.year,stu1.bir1.month,stu1.bir1.day);
}
#pragma mark 3 结构体封装视图的坐标
void structFrame()
{
struct CGPoint{//位置
float x;
float y;
};
struct CGSize{//尺寸
double wigth;
double hight;
};
struct CGFrame{//坐标(包含位置、尺寸)
struct CGPoint point;
struct CGSize size;
};
struct View{
char *color;
struct CGFrame frame;
};
struct View view1={"redColor",{100,50,120,60}};
printf("view color is %s,view.x:%f,view.y:%f,view.w:%lf,view.h:%lf",view1.color,view1.frame.point.x,view1.frame.point.y,view1.frame.size.wigth,view1.frame.size.hight);
}
#pragma mark 4 结构体数组
void structFour()
{
struct Student {
int age;
char *name;
}stu[2]={{23,"Tom"},{21,"Jack"}};
//struct Student man[3]={};
struct Student stu1=stu[0];
printf("数组中第一个学生:age=%d,name=%s",stu1.age,stu1.name);
}
#pragma mark 5 结构体作为函数的参数
struct Person{
int age;
};
void change(struct Person p){
printf("参数传递:%d",p.age);
}
void structFive()
{
struct Person person={24};
change(person);
}
#pragma mark 6 指向结构体的指针
void structSix()
{
struct Person per1={33};
struct Person *per2;
per2 = &per1;
printf("%d\n",per1.age);
printf("%d\n",(*per2).age);
printf("%d",per2->age);
}
int main(int argc, const char * argv[]) {
structSix();
return 0;
}
标签:
原文地址:http://www.cnblogs.com/liuyingjie/p/4941542.html