struct tag
{member-list;
}variable-list;
//描述一个人
struct people
{char name[10];//人名int age;//年龄int idnumber;//身份证
};
struct
{member-list;
}variable-list;
有时候需要通过结构体变量内部成员找到同类型的结构体变量,这就叫结构体的自引用
struct Node
{int data;struct Node next;
};
struct Node
{int data;struct Node* next;
};
typedef struct Node
{int data;struct Node* next;//注意不能写成Node* next
}Node;
//描述一个人
typedef struct people
{char name[10];//人名int age;//年龄int idnumber;//身份证
}people;int main()
{people a = { "limou3434", 30, 44443333 };printf("%s %d %d", a.name, a.age, a.idnumber);return 0;
}
//描述一个人
typedef struct people
{char name[10];//人名int age;//年龄int idnumber;//身份证
}people;int main()
{people a = { "limou3434", 30, 44443333 };printf("%s %d %d\n", a.name, a.age, a.idnumber);people b = { .age = 20, .idnumber = 1234567890, .name = "limou" };printf("%s %d %d\n", b.name, b.age, b.idnumber);return 0;
}
详细看另外一篇文章额外:结构体内存对齐
#include
#include //使用offsetof宏,要包含头文件stddef.h
typedef struct people
{char name[10];//人名int age;//年龄int idnumber;//身份证
}people;
int main()
{people s = { "limou", 12, 88888888 };printf("%zd %zd %zd", offsetof(people, name), offsetof(people, age), offsetof(people, idnumber));
}
将小的类型集中在一起就会一定程度节省结构体的空间
①位段的成员必须是“整型算术类型”:int、unsigned int、signed int、char等
②位段的成员名后边有一个冒号和一个数字
//位段例子,后面的数字代表存储的比特位
struct A
{int a:2;int b:5;int c:10;int d:30;
};
位段主要是用在网络数据传输上,这点涉及较远,暂且不谈
enum 枚举名
{枚举成员1,枚举成员2,…枚举成员n
}
枚举成员的值,从0开始一次递增1。也可以直接在枚举体内进行赋值,赋值成员后的成员,比赋值成员的值大1
//一个枚举体的例子
#include
enum Color//颜色
{RED,YELLOW,GREEN=6,BLUE
};
int main()
{enum Color c = BLUE;//注意最好不要直接赋7,这在C语言可能被允许,但是在C++上可能会提示类型错误,因为1是int类型,而enum Color是一种枚举体类型printf("%d\n", c);printf("%d %d %d %d\n", RED, YELLOW, GREEN, BLUE);
}
①有类型检查
②比宏更加便于调试
③使用方便,一次定义多个常量
④代码可读性提高