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