一、结构体存储
#include<stdio.h> #include<stdlib.h> struct info{ char c; //1 2 4 8 double num; //1 2 4 8 char short int double char ch[9]; //9 10 12 16 }; void main() { printf("%d ",sizeof(struct info)); struct info in={'a',5.2,"hello"}; printf("%p ",&in); printf("%p ",&in.c); printf("%p ",&in.num); printf("%p ",&in.ch); system("pause"); }
二、枚举类型(限定取值)
枚举常量实质是整型数据
#include<stdio.h> #include<stdlib.h> //枚举的一般形式,限定在这个范围内取值 //如果没有一个赋初值,就会从0循环到最后一个,每次加1 //如果第一个赋初值,后面每个加1 //除非自己赋值,否则计算机赋值会让每个枚举常量都不同 enum level{ 司令=5,军长=5,师长,旅长,团长,营长,连长,排长,班长,士兵 }; void main() { enum level l1=司令; enum level l2=军长; enum level l3=师长; printf("%d ",l1); printf("%d ",l2); printf("%d ",l3); system("pause"); }
三、typedef
#include<stdio.h> #include<stdlib.h> typedef int aa; //typedef没有创建数据类型,给已经有的数据类型起一个别名.编译时处理,仅适用于类型 #define zhengshu num //define是替换,预处理,适用于任何场合 void main() { aa zhengshu=10; printf("%d ",num); system("pause"); }
#include<stdio.h> #include<stdlib.h> typedef int I;//给int一个别称 typedef int* IP; void main() { I num=100;//int num=100 IP p=#//int *p=&num printf("%d,%d ",num,*p); printf("%p,%p ",&num,p); system("pause"); }
#include<stdio.h> #include<stdlib.h> void main() { /*int a[10]; int s[10];*/ typedef int s[10];//重定义数组类型 s x; for (int i = 0; i < 10; i++) { x[i]=i; printf("%d ",x[i]); } system("pause"); }
#include<stdio.h> #include<stdlib.h> #include<string.h> struct info{ char name[100]; int num; }; typedef struct info I;//I=struct info typedef struct info* P;//P=struct info* void main() { I s; strcpy(s.name,"yincheng"); s.num=100; printf("%s,%d ",s.name,s.num); P ip=(P)malloc(sizeof(I)); strcpy(ip->name,"yincheng8848"); ip->num=8888; printf("%s,%d ",(*ip).name,ip->num);
free(ip); system("pause"); }
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct tel{ char name[30]; long long num; }T,*P; void main() { printf("%d ",sizeof(struct tel)); printf("%d ",sizeof(T)); printf("%d ",sizeof(P)); T t1; strcpy(t1.name,"yincheng"); t1.num=18288889999; printf("%s,%lld ",t1.name,t1.num); P pt1=(P)malloc(sizeof(T));//malloc之后记得要free strcpy(pt1->name,"尹成"); pt1->num=18611118888; printf("%s,%d ",(*pt1).name,pt1->num); free(pt1); system("pause"); }
四、深拷贝和浅拷贝
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct string{ char *p; int len; }S; //浅拷贝,共享内存 void main1() { S s1,s2; s1.len=10; s1.p=(char *)malloc(sizeof(char)*10); strcpy(s1.p,"hello"); printf("s1.p=%s ",s1.p); s2.len=s1.len; s2.p=s1.p; *(s1.p)='K'; printf("s2.p=%s ",s2.p); system("pause"); } //深拷贝,拷贝内存内容 void main() { S s1,s2; s1.len=10; s1.p=(char *)malloc(sizeof(char)*10); strcpy(s1.p,"hello"); printf("s1.p=%s ",s1.p); s2.len=s1.len; s2.p=(char *)malloc(sizeof(char)*10); strcpy(s2.p,s1.p); *(s1.p)='K'; printf("s2.p=%s ",s2.p); system("pause"); }
浅拷贝
深拷贝