一. 结构体的定义和赋值
结构体: 一系列不同类型的数据的结合
强调:类型 != 变量
结构体名代表的只是结构体类型,没有内存空间。
结构体中的成员可以单独使用
//结构体赋值方式一:
struct Student stu1 = {"ruby",22};
//结构体赋值方式二:
struct Student stu2;
strcpy(stu2.name, "ruby");
stu2.age = 22;
//结构体赋值方式三
struct Student{
char name[20] ;
int age ;
}lucy = {"ruby",22};
二. 结构体数组以及初始化
#include <stdio.h>
int main(int argc, const char * argv[])
{
//方式1:
struct Student{
int age;
char *name;
}stu[3]={{22,"peter"},{33,"tom"},{23,"tiger"}};
for (int i = 0; i < 3; i ++) {
printf("%s\t", stu[i].name);
}
printf("\n");
//方式2:
struct Student stu1[3] ={{22,"peter"},{33,"tom"},{23,"tiger"}};
for (int i = 0; i < 3; i ++) {
printf("%s\t", stu1[i].name);
}
printf("\n");
//方式3:
struct Student stu2[3];
stu2[0] = (struct Student){22,"peter1"};
stu2[1] = (struct Student){23,"peter2"};
stu2[2] = (struct Student){24,"peter3"};
for (int i = 0; i < 3; i ++) {
printf("%s\t", stu2[i].name);
}
printf("\n");
return 0;
}
三. 结构体指针
struct Student(){
char name[20];
int age;
};
int main(){
struct Student *stud;
//这里是申请连续的 4个struct Student 类型结构体大小的内存空间
stud = (Student *)malloc(sizeof(struct Student) * 4);
//用menset函数初始化结构体数组,全部为 0 ;
memset(stud,0,sizeof(struct Student) * 4);
int i ;
//遍历赋值
for(i = 0 ; i < 4 ; i++){
(stud + i)->age = 20 + i;
(stud + i)->name = "ruby";
}
}
四. 用结构体实现单链表
struct Node{
int data; //记录当前节点
Node * next;//记录下一个节点的内存地址
};
int enqueNode(Node *head,int data){
//申请一个新的节点,node记录的是新节点的内存地址
Node *node = (Node *)malloc(sizeof(struct Node));
if (node == NULL){
return 0;
}
node->data = data;
node->next = NULL;
Node *p = head;//把传递进来的内存地址赋值给指针变量p
while (p->next != NULL){
p = p->next; //指针做位移操作
}
p->next = node;//将申请到的新的地址赋值给指针变量p的next
return 1;
}
int main(){
int i;
int num = 10;
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;
}
五. 知识点
malloc函数和calloc的区别:
//malloc函数申请到的空间,整块是连续的
list = (Node *)malloc(sizeof(struct Node));
//而calloc申请到的空间,整块有可能是不连续的
list = (Node *)calloc(10,sizeof(struct Node));