1. 结构体定义和初始化
struct Student
{
char name[20];
int age;
char gender[10];
int classId;
};
struct Student2
{
char name[20];
int age;
char gender[10];
int classId;
}Zeking;
struct {
char name[20];
int age;
char gender[10];
int classId;
}stud3, stu4, stu5;
struct People{
char name[20];
int age;
}Lucy = {"Lucy",90};
int main(){
struct Student stu1;
struct People people1 = {"Zeking",20};
struct People people2;
people2.age = 1;
strcpy(people2.name, "lucy");
people1.age = 10;
printf("%s,%d \n", people1.name, people1.age);
system("pause");
return 0;
}
2. 结构体数组 结构体指针
struct People2{
char *name;
int age;
}Lucy2 = { "Lucy", 90 };
int main(){
int i;
struct People2 stu[3] = { { "Zeking", 30 }, { "David", 32 }, { "Suci", 28 } };
struct People2 s[5];
for (i = 0; i < 5; i++){
s[i].age = 20 + i;
s[i].name = "lucy";
}
for (i = 0; i < 5; i++){
printf("s %d:%s,%d\n",i,s[i].name,s[i].age);
}
struct People2 *p = stu;
struct People2 *p2;
p2 = (People2 *)malloc(sizeof(struct People2) *4);
printf("%#x \n",&p2);
memset(p2, 0, sizeof(struct People2) * 4);
for (i = 0; i < 4; i++){
p2[i].age = 20 + i;
p2[i].name = "zeking";
}
for (i = 0; i < 4; i++){
printf("p2 : %d:%s,%d\n", i, (p2 + i)->name, (p2 + i)->age);
}
system("pause");
return 0;
}
3 . 结构体 里面添加函数指针
struct Man{
int age;
char *name;
int(*Msg)(char *,int);
};
int message(char *str, int age){
MessageBox(0, TEXT("hello"), TEXT("Lijian"), 0);
return 0;
}
int main(){
struct Man man;
man.age = 40;
man.name = "Zeking";
man.Msg = message;
man.Msg(man.name,man.age);
system("pause");
return 0;
}
4. 结构体中添加结构体指针成员变量
struct Node {
int data;
Node * next;
};
int enqueNode(Node *head, int data) {
Node * node = (Node *)malloc(sizeof(Node));
if (node == NULL) {
return 0;
}
node->data = data;
node->next = NULL;
Node *p = head;
while(p->next != NULL) {
p = p->next;
}
p->next = node;
return 1;
}
int main() {
int num = 10;
int i = 0;
Node * list;
list = (Node *)malloc(sizeof(struct Node));
list->data = 0;
list->next = NULL;
for (i = 0; i < num; i++) {
enqueNode(list, i+1);
}
while (list->next != NULL)
{
printf("%d \n", list->data);
list = list->next;
}
system("pause");
return 0;
}
5. typedef 指令
typedef int _in;
typedef char * string;
typedef int(*PFI)(char *, char *);
typedef Tnode * Treeptr;
typedef struct Tnode {
char *word;
int count;
Treeptr left;
Treeptr right;
} BinaryTreeNode;
int fun(char *, char *) {
return 0;
}
int main() {
_in a = 20;
printf("%d\n", a);
string str;
str = "hello world";
PFI fp;
fp = fun;
char * ch;
ch = "hello world";
BinaryTreeNode* node;
node = (BinaryTreeNode *) malloc(sizeof(BinaryTreeNode));
system("pause");
return 0;
}
6. 公用体 ,枚举
union MyUnion
{
int a;
char b;
float c;
};
int main() {
MyUnion unio;
unio.a = 10;
unio.b = 'a';
unio.c = 1.2f;
printf("a: %#x, b: %#x, c: %#x\n", &unio.a, &unio.b, &unio.c);
printf("a: %d, b: %c, c: %f\n", unio.a, unio.b, unio.c);
system("pause");
return 0;
}
enum {
monday = 10,
saturday, 、、
sunday,
};