@(C语言)
[toc]
定义
一系列不同类型的数据的结合
使用
//结构体
struct Student{
char name[20];
int age;
char gender[10];
int classId;
};
//结构体
struct Student{
char name[20];
int age;
char gender[10];
int classId;
}Lucy;
//匿名全局的结构体,直接分配内存
struct{
char name[20];
int age;
char gender[10];
}stu3;
类型!=变量。
结构体名代表的只是结构体类型,没有内存空间。
结构体中的成员可以单独使用
结构体数组
/////结构体数组//////
int main(){
//初始化
struct Student stu[3] ={{"Lucy",30},{"lilei",33},{"Hanmeimei",35}};
struct Student s[5];
for (int i=0; i<5; i++) {
s[i].age=20+i;
strcpy(s[i].name,"lucy");
}
for (int i=0; i<5; i++) {
printf("s %d: %s %d \n",i,s[i].name,s[i].age);
}
return 0;
}
输出:
s 0: lucy 20
s 1: lucy 21
s 2: lucy 22
s 3: lucy 23
s 4: lucy 24
- 初始化
int i;
struct Student * stud ;
stud =(struct Student *)malloc(sizeof(struct Student)*4);
memset(stud,0,sizeof(struct Student)*4);
for (i=0; i<4; i++) {
(stud+i)->age =20+i;
strcpy((stud+i)->name,"lucy");
strcpy(stud[i].name,"cailei");
stud[i].age =30+i;
}
for (int i=0; i<4; i++) {
printf("s %d: %s %d \n",i,stud[i].name,stud[i].age);
}
输出:
s 0: cailei 30
s 1: cailei 31
s 2: cailei 32
s 3: cailei 33
实现个单链表
struct Node{
int data;
struct Node *next;
};
int enqueNode(struct Node * head,int data){
struct Node * node=(struct Node *)malloc(sizeof(struct Node));
node->data =data;
node->next = NULL;
struct Node *p=head;
while (p->next!=NULL) {
p=p->next;
}
p->next =node;
return 1;
}
int main(){
struct Node * list;
list = (struct Node*)malloc(sizeof(struct Node));
// list = (struct Node*)calloc(10,sizeof(struct Node));
list->data =0;
list->next =NULL;
int i ;
int num =10;
for (i =0; i<num; i++) {
enqueNode(list,i+1);
}
while (list->next!=NULL) {
printf("%d \n",list->data);
list =list->next;
}
}
输出:
0
1
2
3
4
5
6
7
8
9