C语言自定义类型struct

来源:互联网 发布:最内涵最污的段子知乎 编辑:程序博客网 时间:2024/06/11 08:05

C语言的类型:

内置类型——char,short,int,float,double;

自定义类型——struct结构体,union联合体,enum枚举类型。


C语言允许用户自己建立由不同类型数据组成的组合型的数据结构,它称为结构体


声明结构体&初始化结构体变量

#include<stdio.h>#include<string.h>#include<stdlib.h>//对结构体变量初始化struct Student{char id[5];char name[10];int age;char sex[3];}s2={"0002","Mary",15,"女"};int main(){struct Student s1={"0001","Tom",10,"男"};struct Student s3;   //定义变量strcpy(s3.id,"0003");   //对结构体变量s3各成员变量赋值,·是作用域访问符strcpy(s3.name,"John");s3.age=13;strcpy(s3.sex,"男");system("PAUSE");return 0;}


多重结构体变量访问

#include<stdio.h>#include<string.h>#include<stdlib.h>//结构体变量内成员变量是结构体struct Date{int year;int month;int day;};struct Student{char id[5];char name[10];int age;char sex[3];struct Date date;};int main(){struct Student s4;   //定义变量strcpy(s4.id,"0004");   //对结构体变量s4各成员变量赋值,·是作用域访问符strcpy(s4.name,"Jane");s4.age=8;strcpy(s4.sex,"女");s4.date.year=2009;   //多重结构体成员变量赋值s4.date.month=5;s4.date.day=24;system("PAUSE");return 0;}

根据“用户输入”初始化结构体

用户输入信息需要访问到结构体变量所在的内存空间地址

#include<stdio.h>#include<string.h>#include<stdlib.h>struct Student{char id[5];char name[10];int age;char sex[3];};int main(){struct Student s1;printf("input id:>");scanf("%s",s1.id);   //用字符数组s1.id的地址接收用户输入的idprintf("input age:>");scanf("%d",&s1.age);   //用整型数组s1.age的地址接收用户输入的agesystem("PAUSE");}


定义结构体类型数组,通过数组同时初始化多个结构体

#include<stdio.h>#include<string.h>#include<stdlib.h>struct Student{char id[5];char name[10];int age;char sex[3];};void main(){struct Student S[2]={{"0001","Newton",35,"男"},{"0002","Lagrange",30,"男"}};   //通过数组同时初始化多个结构体for(int i=0;i<2;++i){printf("id=%s,name=%s,age=%d,sex=%s\n",S[i].id,S[i].name,S[i].age,S[i].sex);}system("PAUSE");}

定义结构体指针,通过指针指向符->访问结构体成员变量

#include<stdio.h>#include<string.h>#include<stdlib.h>struct Student{char id[5];char name[10];int age;char sex[3];};void main(){int a =10;int *pa=&a;Student s1={"0001","Euler",32,"男"};printf("id=%s,name=%s,age=%d,sex=%s\n",s1.id,s1.name,s1.age,s1.sex);struct Student *ps=&s1;   //指向结构体的“结构体类型指针”printf("id=%s,name=%s,age=%d,sex=%s\n",ps->id,ps->name,ps->age,ps->sex);   //通过指针指向符->访问结构体成员变量system("PAUSE");}


线性链表

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<malloc.h>#define ElemType intstruct Node{ElemType data;struct Node *next;};typedef Node* List;void InitList(List *head){*head=NULL;}void CreateList(List *head){*head=(Node *)malloc(sizeof(Node));(*head)->data=1;(*head)->next=NULL;Node *p=*head;for(int i=2;i<=10;++i){Node *s=(Node *)malloc(sizeof(Node));s->data=i;s->next=NULL;p->next=s;p=s;}}void ShowList(List head){Node *p=head;while(p!=NULL){printf("%d-->",p->data);p=p->next;}printf("Over!\n");}void main(){List mylist;InitList(&mylist);CreateList(&mylist);ShowList(mylist);system("PAUSE");}


原创粉丝点击